Kenneth SaksSenior Staff EngineerSUN Microsystems
Enterprise JavaBeansTM
(EJBTM) 3.1
2
Agenda
• Background• Proposed Functionality• Summary• Q & A
3
EJB 3.0 Specification (JSR 220)
• Features> Simplified EJB API> Java Platform Persistence API
• Focus on ease-of-use> Annotations > Intelligent defaults> Fewer classes needed
• Very well received within the community> But... more work is needed
4
EJB 3.1 Specification
• Goals> Continued focus on ease-of-use> New features
• JSR (Java Specification Request) 318> Launched in August 2007
– Java Persistence API will evolve separately ( JSR 317 )
> Early Draft February 2008 > Public Draft October 2008
• Caveat – APIs still subject to change
5
Agenda
• Introduction• Proposed Functionality • Summary• Q & A
6
Ease of Use Improvements
• Optional Local Business Interfaces• Simplified Packaging• EJB “Lite” • Portable Global JNDI Names• Simplified Unit Testing
7
Session Bean with Local Business Interface
<<interface>com.acme.Hello
String sayHello()
com.acme.HelloBean
public String sayHello() { ... }
@EJB private Hello h;
...
h.sayHello();
HelloBean Client
8
Optional Local Business Interfaces
• Sometimes local business interface isn't needed• Better to completely remove interface from
developer's view than to generate it• Result : “no-interface” view
> Just a bean class> public bean class methods exposed to client> Same behavior and client programming model
as Local view– Client acquires an EJB component reference instead
of calling new()
9
Session Bean with “No-interface” View@Statelesspublic class HelloBean {
public String sayHello(String msg) { return “Hello “ + msg; }
}
10
No-interface View Client
@EJB HelloBean h;
...
h.sayHello(“bob”);
11
Web/EJB Application in JavaTM EE Platform 5
foo.ear
WEB-INF/web.xmlWEB-INF/classes/ com/acme/FooServlet.classWEB-INF/classes com/acme/Foo.class
foo_web.war
com/acme/FooBean.classcom/acme/Foo.class
foo_ejb.jar
foo.ear
lib/foo_common.jar
com/acme/Foo.class
WEB-INF/web.xmlWEB-INF/classes/ com/acme/FooServlet.class
foo_web.war
com/acme/FooBean.class
foo_ejb.jar
OR
12
foo.war
WEB-INF/classes/ com/acme/FooServlet.class
WEB-INF/classes/ com/acme/FooBean.class
Web/EJB Application in JavaTM EE Platform 6
13
Simplified Packaging
• Goal is to remove an artificial packaging restriction> Not to create a new flavor of EJB component
• EJB component behavior is independent of packaging> One exception : module-level vs. component-level
environment
• No new restrictions placed on .war > Deploy .war stand-alone OR within an .ear
14
EJB “Lite”
• Small subset of EJB 3.1 API for use in Web Profile• Broaden the availability of EJB technology
> Without losing portability
• Same exact Lite application can be deployed to Web Profile and Full Profile > Thanks to simplified .war packaging
• Open issue : whether Web Profile will require EJB Lite
15
“Lite” vs. Full Functionality
Lite • Local Session Beans• Annotations / ejb-
jar.xml• CMT / BMT• Declarative Security• Interceptors
• (Also requires JPA 2.0 API / JTA 1.1 API )
Full = Lite + the following:• Message Driven Beans• EJB Web Service
Endpoints• RMI-IIOP
Interoperability• 2.x / 3.x Remote view• 2.x Local view• Timer Service• CMP / BMP
16
Session Bean Exposing a Remote View@Stateless@Remote(Hello.class)public class HelloBean implements Hello {
public String sayHello(String msg) { return “Hello “ + msg; }
}
17
Remote Clients
// Remote client in a Java EE container@EJB Hello hello;
// Remote client in a Java SE environmentHello hello = (Hello) new InitialContext().lookup(???);
Question : How does the caller find the target EJB component?
18
Problems with “Global” JNDI Names
• Not portable> Global JNDI namespace is not defined in Java EE
platform specification > Vendor-specific configuration needed for each
deployment
• No standard syntax> Can names contain : “.”, “_”, “/” ?
• Not clear which resources have them> Local interfaces?
19
Portable Global JNDI Names
“java:global[/<app-name>]/<module-name>/<bean-name>”
// Client in a Java EE container@EJB(mappedName= ”java:global/hello/HelloBean”) Hello hello;
// Client in a Java SE environmentHello hello = (Hello) new InitialContext() lookup(“java:global/hello/HelloBean”);
20
EJB Component Testing
• It's too hard to test EJB components, especially the Local view > Forced to go through Remote facade or Web tier> Separate JVM™ instances needed for server and client
• Support for running in Java SE exists, but...> Not present in all implementations> No standard API for bootstrapping, component discovery,
shutdown etc.
21
Example: No-interface Stateless Session Bean
@Statelesspublic class BankBean {
@PersistenceContext EntityManager accountDB;
public String createAccount(AccountDetails d) { ... }
public void removeAccount(String accountID) { ... }
}
22
Example: Embeddable APIpublic class BankTester {
public static void main(String[] args) { EJBContainer container = EJBContainer.createEJBContainer();
// Acquire EJB component reference BankBean bank = (BankBean)container.getContext(). lookup(“java:global/bank/BankBean”);
testBank(bank); ... container.close(); }
23
Example : Embeddable API (cont.)
% java -classpath bankClient.jar : bank.jar : javaee.jar : <vendor_rt>.jar com.acme.BankTester
24
Embeddable API
• Execute enterprise beans in a Java SE environment• “Single application” model• Same EJB component behavior / lifecycle as
server-side> CMT, injection, threading guarantees, etc.
• Only EJB “Lite” functionality required to be available
25
New Features
• Singletons• Application startup / shutdown callbacks• Calendar-based timer expressions• Automatic timer creation• Simple Asynchrony
26
Singletons
• New session bean component type> One singleton bean instance per application per JVM> Provides easy sharing of state within application> Designed for instance-level concurrent access
• Lots in common with stateless / stateful beans> Client views (No-interface , Local, Remote, Web Service) > CMT / BMT> Container services: timer service, injection, etc.> Method authorization
27
Simple Singleton
@Singletonpublic class SharedBean {
private SharedData shared;
@PostConstruct private void init() { shared = ...; }
public int getXYZ() { return shared.xyz; }
}
28
Singleton Client
@Stateless public class FooBean {
@EJB private SharedBean shared;
public void foo() { int xyz = shared.getXYZ(); ... }
}
29
Singleton Concurrency Options
• Single threaded (default)> Container serializes concurrent requests
• Container Managed Concurrency> Concurrency via method-level locking metadata
– Read lock (Shared): allow any number of concurrent accesses
– Write lock (Exclusive) : ensure single-threaded access
> Container blocks invocations until they can proceed– ...or until app-specified timeout is reached
• Bean Managed Concurrency > Like Java Servlet API threading model
30
Read-Only Singleton with Container Managed Concurrency
@Singletonpublic class SharedBean {
private SharedData shared;
@Lock(READ) public int getXYZ() { return shared.xyz; }
...}
31
Read-Mostly Singleton with Container Managed Concurrency
@Singleton@Lock(READ)public class SharedBean {
private SharedData shared;
public int getXYZ() { return shared.xyz; }
@Lock(WRITE) public void update(...) { // update shared data ... }
32
Concurrent Access Timeouts
@Singletonpublic class SharedBean {
private SharedData shared;
@Lock(READ) @AccessTimeout(1000) public int getXYZ() { return shared.xyz; }
@Lock(WRITE) public void update(...) { // update shared data }
33
Read-Mostly Singleton with Bean Managed Concurrency
@Singleton@ConcurrencyManagement(BEAN)public class SharedBean {
private SharedData shared;
synchronized public int getXYZ() { return shared.xyz; }
synchronized public void update(...) { // update shared data ... }
34
Startup / Shutdown Callbacks
@Singleton@Startuppublic class StartupBean {
@PostConstruct private void onStartup() { ... }
@PreDestroy private void onShutdown() { ... }
35
Timer Service Features
• Calendar-based timeout expressions • Automatic timer creation• Non-persistent timers
36
Calendar Based Timeouts
• “Cron”-like semantics with improved syntax• Usable with automatic or programmatic timers • Named attributes
> second, minute, hour ( default = “0” )> dayOfMonth, month, dayOfWeek, year (default = “*”)
37
Calendar Based Timeouts
// The last Thursday in November at 2 p.m.(hour=”14”, dayOfMonth=”Last Thu”, month=”Nov”)
// Every weekday morning at 3:15 a.m.(minute=”15”, hour=”3”, dayOfWeek=”Mon-Fri”)
// Every five minutes (minute=”*/5”, hour=”*”)
38
Expression Attribute Syntax
• Single value : minute = “30”• List : month = “Jan, Jul, Dec”• Range : dayOfWeek = “Mon-Fri”• Wildcard : hour = “*”• Increment : minute = “*/10”
39
Automatic Timer Creation
• Container creates timer automatically upon deployment
• Logically equivalent to one createTimer() invocation• Each automatic timer can have its own timeout
callback method
40
Automatic Timer Creation
@Stateless public class BankBean { @PersistenceContext EntityManager accountDB; @Resource javax.mail.Session mailSession;
// Callback the 1st of each month at 8 a.m.
@Schedule(hour=”8”, dayOfMonth=”1”) void sendMonthlyBankStatements() { ... }
}
41
Non-persistent Timers
• Timers without persistent delivery guarantee • Only live for duration JVM instance• Good fit for Singleton cache updates• Better performance for fine-grained timeouts
42
Non-Persistent Timer Example
@Singleton public class CacheBean {
private Cache cache;
@Schedule(minute=”*/5”,hour=”*”,persistent=false) private void updateCache() { ... }
...
}
43
Simple Asynchrony
• Different styles> Local concurrency
– E.g : break large piece of work into independent tasks
> Async RPC
• Too difficult with existing APIs> JMS API – complex API / lots of configuration> Threads – not well integrated with component model
• Approach : integrate asynchronous support directly into session bean components
44
Simple Local Concurrent Computation
@Stateless public class DocBean {
@Resource SessionContext ctx;
public void processDocument(Document document) { DocBean me = ctx.getBusinessObject(DocBean.class); me.doAnalysisA(document); me.doAnalysisB(document); }
@Asynchronous public void doAnalysisA(Document d) {...} @Asynchronous public void doAnalysisB(Document d) {...}
}
45
Asynchronous Operation Results -- Client@EJB Processor processor;
Task task = new Task(...);
Future<int> computeTask = processor.compute(task);
...
int result = computeTask.get();
46
@Asynchronous on Bean Class
@Stateless public class ProcessorBean implements Processor {
@PersistenceContext EntityManager db;
@Asynchronous public Future<int> compute(Task t) { // perform computation int result = ...;
return new javax.ejb.AsyncResult<int>(result); }
}
47
@Asynchronous on Interface
public interface Processor {
@Asynchronous public Future<int> compute(Task t);
}
48
@Asynchronous on Interface
@Stateless @Local(Processor.class)public class ProcessorBean {
@PersistenceContext EntityManager db;
public int compute(Task t) { // perform computation int result = ...;
return result; }
}
49
Async Behavior
• Transactions> No transaction propagation from caller to callee
• Method authorization> Works the same as for synchronous invocations
• Exceptions> Exception thrown from target invocation available via
Future<V>.get()
• SessionContext.isCancelled() allows bean to check for cancellation during processing
50
Agenda
• Introduction• Proposed Functionality• Summary• Q & A
51
Summary
• EJB 3.1 Specification (JSR 318)• Part of Java EETM Platform 6• Goals
> Ease-of-use> New Features
52
For More Information
• JSR 318 Home : http://jcp.org/en/jsr/detail?id=318> Send comments to [email protected]
• Blog : http://blogs.sun.com/kensaks/• Reference Implementation : GlassFish project V3
> http://glassfish.dev.java.net> [email protected]
53
Agenda
• Introduction• Proposed Functionality• Summary• Q & A
Kenneth SaksSenior Staff EngineerSUN Microsystems
Enterprise JavaBeansTM
(EJBTM) 3.1
Top Related