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
3
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
4
6. Ease of Use Improvements
• Optional Local Business Interfaces
• Simplified Packaging
• EJB “Lite”
• Portable Global JNDI Names
• Simplified Unit Testing
6
7. Session Bean with
Local Business Interface
HelloBean Client <<interface>
com.acme.Hello
@EJB String sayHello()
private Hello h;
...
h.sayHello(); com.acme.HelloBean
public String
sayHello()
{ ... }
7
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()
8
9. Session Bean with “No-interface”
View
@Stateless
public class HelloBean {
public String sayHello(String msg) {
return “Hello “ + msg;
}
}
9
11. Web/EJB Application in
TM
Java EE Platform 5
foo.ear foo.ear
lib/foo_common.jar
foo_web.war
WEB-INF/web.xml com/acme/Foo.class
WEB-INF/classes/
com/acme/FooServlet.class foo_web.war
WEB-INF/classes
com/acme/Foo.class OR WEB-INF/web.xml
WEB-INF/classes/
com/acme/FooServlet.class
foo_ejb.jar
com/acme/FooBean.class foo_ejb.jar
com/acme/Foo.class
com/acme/FooBean.class
11
12. Web/EJB Application in
TM
Java EE Platform 6
foo.war
WEB-INF/classes/
com/acme/FooServlet.class
WEB-INF/classes/
com/acme/FooBean.class
12
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
13
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
14
15. “Lite” vs. Full Functionality
Lite Full = Lite + the following:
• Local Session Beans • Message Driven Beans
• Annotations / ejb- • EJB Web Service
jar.xml Endpoints
• CMT / BMT • RMI-IIOP
• Declarative Security Interoperability
• Interceptors • 2.x / 3.x Remote view
• 2.x Local view
• (Also requires JPA 2.0 • Timer Service
API / JTA 1.1 API ) • CMP / BMP 15
16. Session Bean Exposing a Remote
View
@Stateless
@Remote(Hello.class)
public class HelloBean implements Hello {
public String sayHello(String msg) {
return “Hello “ + msg;
}
}
16
17. Remote Clients
// Remote client in a Java EE container
@EJB Hello hello;
// Remote client in a Java SE environment
Hello hello = (Hello)
new InitialContext().lookup(???);
Question : How does the caller find the
target EJB component?
17
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?
18
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 environment
Hello hello = (Hello) new InitialContext()
lookup(“java:global/hello/HelloBean”);
19
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.
20
21. Example: No-interface Stateless
Session Bean
@Stateless
public class BankBean {
@PersistenceContext EntityManager accountDB;
public String createAccount(AccountDetails d) {
...
}
public void removeAccount(String accountID) {
...
}
}
21
22. Example: Embeddable API
public 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();
}
22
23. Example : Embeddable API (cont.)
% java -classpath bankClient.jar :
bank.jar :
javaee.jar :
<vendor_rt>.jar
com.acme.BankTester
23
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
24
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
26
27. Simple Singleton
@Singleton
public class SharedBean {
private SharedData shared;
@PostConstruct private void init() {
shared = ...;
}
public int getXYZ() {
return shared.xyz;
}
}
27
28. Singleton Client
@Stateless
public class FooBean {
@EJB
private SharedBean shared;
public void foo() {
int xyz = shared.getXYZ();
...
}
}
28
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
29
30. Read-Only Singleton with Container
Managed Concurrency
@Singleton
public class SharedBean {
private SharedData shared;
@Lock(READ)
public int getXYZ() {
return shared.xyz;
}
...
}
30
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
...
}
31
32. Concurrent Access Timeouts
@Singleton
public class SharedBean {
private SharedData shared;
@Lock(READ)
@AccessTimeout(1000)
public int getXYZ() {
return shared.xyz;
}
@Lock(WRITE)
public void update(...) {
// update shared data
}
32
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
...
}
33
35. Timer Service Features
• Calendar-based timeout expressions
• Automatic timer creation
• Non-persistent timers
35
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 = “*”)
36
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=”*”)
37
38. Expression Attribute Syntax
• Single value : minute = “30”
• List : month = “Jan, Jul, Dec”
• Range : dayOfWeek = “Mon-Fri”
• Wildcard : hour = “*”
• Increment : minute = “*/10”
38
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
39
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() {
...
}
}
40
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
41
42. Non-Persistent Timer Example
@Singleton public class CacheBean {
private Cache cache;
@Schedule(minute=”*/5”,hour=”*”,persistent=false)
private void updateCache() { ... }
...
}
42
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
43
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) {...}
}
44
45. Asynchronous Operation Results --
Client
@EJB Processor processor;
Task task = new Task(...);
Future<int> computeTask = processor.compute(task);
...
int result = computeTask.get();
45
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);
}
}
46
47. @Asynchronous on Interface
public interface Processor {
@Asynchronous
public Future<int> compute(Task t);
}
47
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;
}
}
48
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
49