Middleware Technology (J2EE/EJB) Entity Bean (JBoss EJB 3.0 tutorial)
Enterprise JavaBeans EJB component typesdonatas/PSArchitekturaProjektavimas/slides...@EJB means that...
Transcript of Enterprise JavaBeans EJB component typesdonatas/PSArchitekturaProjektavimas/slides...@EJB means that...
Enterprise JavaBeans
EJB component types
Recommended book
Introduction to EJB 3
EJB 3.1 component examplepackage examples;
import javax.ejb.Stateless;
@Statelesspublic class HelloBean {
public String hello() {return “Hello, World!”;
}}
Introduction to EJB 4
Introduction to EJB 5
Essential EJB 3.x characteristics Business logic may be separated from middleware
services invocation (security, transactions, …) –implicit middleware
new middleware can be added without changing components source code
Component programming model is not EJB specific –components are simple POJO classes
Component (as a simple class) can be used in different frameworks or with plain Java
Introduction to EJB 6
EJB component types Service components (stateless)
Technical name: Stateless session beans
Session components (stateful)
Technical name: Stateful session beans
Singleton components
Technical name: Singleton session beans
Messaging components
Technical name: Message-driven beans
Introduction to EJB 7
Stateless session beans A stateless session bean is a bean that holds
conversations that span a single method call. After any method call, the container may choose to
destroy a stateless session bean, or recreate it, clearing itself out of all information pertaining to past invocations
Stateless session beans can contain state that is not specific to any one client (e.g., DB connection) You can keep this state in a private variables. So long as
you’re willing to lose the data in your private variable at any time, you’ll be fine
Introduction to EJB 8
Stateless session bean example@Statelesspublic class HelloBean {
public String hello(String name) {return “Hello, ”+name;
}public String goodBye(String name) {
return “Bye, ”+name;}
}
Introduction to EJB 9
Stateful session beans A stateful session bean is a bean that is designed to service
business processes that span multiple method requests or transactions.
To accomplish this, stateful session beans retain state on behalf of an individual client. If a stateful session bean’s state is changed during a method
invocation, that same state will be available to that same client upon the following invocation.
It is highly recommended to implement at least one method annotated with @Remove (if CDI is not used) After client executes this method, container destroys the stateful
session bean instance
If CDI is being used, do not implement/call method annotated with @Remove
Introduction to EJB 10
Stateful session bean example@Statefulpublic class MyBean {
private String name;
public void setName(String name) {this.name = name;
}
public String sayHello() {return “Hello, “ + this.name;
}
public String sayGoodbye() {return “Bye, “ + this.name;
}}
Introduction to EJB 11
Thread management The EJB container takes care of servicing concurrent requests
from clients without making the programmer to write multithreading code to handle them No two threads may access a single instance of Stateless or Stateful
component
EJB containers provide built-in thread management support It can instantiate multiple instances of the bean—maintain a pool
of bean instances—to efficiently service the concurrent client requests
EJB component programmer does not have to write thread-safe code This is valid for Stateless and Stateful components only
Singleton components are being discussed further
Introduction to EJB 12
Singleton session beans Singleton session beans:
are identified by the @Singleton annotation and are instantiated once per application
The existing instance is shared by clients and supports concurrent access
By default the container is responsible for deciding whenever a singleton bean is created The developer can instruct the container to initialize the bean
during application startup, using the @Startup annotation.
@Startup annotation permits defining dependencies on other singleton beans The container must initialize all startup singletons before
starting to deliver any client requests
Introduction to EJB 13
Singleton session beans A singleton bean maintains state between client invocations
This state does not survive application shutdown
In order to deal with concurrent client invocations the developer must define a concurrency strategy: Container-managed concurrency (CMC) - the container manages
the access to the bean instance. This is the default strategy. Annotation @Lock may be used to control CMC
Bean-managed concurrency (BMC) - the container takes no intervention in managing concurrency, allowing concurrent access to the bean, and deferring client invocation synchronization to the developer. Class must be annotated with @ConcurrencyManagement(BEAN)
With BMCs it is legal to use synchronization primitives like synchronized and volatile in order to coordinate multiple threads from different clients
Introduction to EJB 14
Container-managed concurrency The container manages concurrency using annotation @Lock. Each method is associated to a read or a write lock.
A READ lock indicates that the method can be accessed by many concurrent invocations.
A WRITE lock indicates that the method can only be invoked by one client at a time.
By default the value of the locking attribute is WRITE.
Whenever a method with write locking has concurrent accesses, the container allows one of them to execute it and holds the other ones until the method becomes available.
The clients on hold will wait indefinitely, unless the @AccessTimeout annotation is used, which allows to define a maximum time (in milliseconds) that a client will wait, throwing a ConcurrentAccessTimeoutException as soon as the timeout is reached.
Introduction to EJB 15
Singleton session bean example@Startup @Singleton
public class CounterBean implements Counter {
private int count;
@PostConstruct void init() {
count = 0;
}
@Lock(READ) public int getCount() {
return count;
}
@AccessTimeout(1000)
@Lock(WRITE)
public int incrementCount() {
return ++count;
}
}Introduction to EJB 16
Memory management: stateless session bean pooling
Introduction to EJB 17
Any stateless session bean instance can service any client request.
These are instances of one and the
same component
Memory management: stateful session beans Only effect of pooling
Bean’s state does not allow to reuse bean for other client
The same problem as with multiple programs in OS –how to reuse RAM
Swapping
For stateful session beans this is called passivation and activation
Introduction to EJB 18
Introduction to EJB 19
Passivation of a stateful bean
Introduction to EJB 20
Activation of a stateful bean
Memory management: stateful session bean annotations @PrePassivate
Annotates the method that will be called before passivation of the bean
@PostActivate
Annotates the method that will be called after activation of the bean
Introduction to EJB 21
Memory management: conclusions Stateless and stateful session beans:
Pros: no need to care about concurrency – we do not have to write thread-safe code
Cons: bigger memory consumption (by component pools)
Singleton beans:
Pros: low memory consumption – a single component’s instance only
Cons: programmer has to deal with Locks and concurrency issues
Introduction to EJB 22
Life-cycle management: annotations @PostConstruct
Annotated method is called after the instance of a component was constructed
@PreDestroy
Annotated method is called before the instance of a component will be destroyed
Introduction to EJB 23
Asynchronous communication It can be used with all types of session beans.
The spec defines that with asynchronous invocations the control must return to the client before the container dispatches the invocation to the bean instance.
This takes the use of session beans into a whole new level, permitting the developer to take benefit from the potential of having asynchronous invocations to session beans, allowing a client to trigger parallel processing flows
Introduction to EJB 24
Asynchronous communication: example@Resource SessionContext ctx;
@Asynchronouspublic Future<String> sayBye() {String bye = executeLongQuery();if (!ctx.wasCancelCalled()){bye += executeSecondLongQuery();
}return new AsyncResult<String>(bye);
}
Introduction to EJB 25
Asynchronous communication: example@EJB Bye byeEjb;
public void invokeSayBye() {
Future<String> futStr = byeEjb.sayBye();
... Do other important things...
String result = futStr.get();
}
Introduction to EJB 26
Timer service@Statelesspublic class TimerEJB {
@Schedule(dayOfWeek="Mon")public void itIsMonday(Timer timer) { ...
}
@Schedule(dayOfMonth="Last")public void itIsEndOfMonth(Timer timer) {
...}
}
Introduction to EJB 27
Timer service
Introduction to EJB 28
Schedule syntax is similar to UNIX/Linux cron tool Examples:Every Tuesday at 7.30am@Schedule(hour = "7", minute = "30", dayOfWeek = "Tue")
From Monday to Friday, at 7, 15 and 20@Schedule(hour = "7, 15, 20", dayOfWeek = "Mon-Fri")
Every hour on Sundays@Schedule(hour = "*", dayOfWeek = "0")
Last Friday of December, at 12@Schedule(hour = "12", dayOfMonth = "Last Fri", month="Dec")
Dynamic schedules are possible too:
ScheduleExpression expression=new ScheduleExpression(); expression.second("*/1").minute("*").hour("*");
How component B can call component A@Stateful // or @Stateless
@SessionScoped // or other scopes
public class A {
...
}
@Stateful // or @Stateless
public class B {
@EJB
private A a;
public void mb() {
a.ma();
...
}
}Introduction to EJB 29
@Stateful // or @Stateless
public class B {
@Inject
private A a;
public void mb() {
a.ma();
...
}
}
How component B can call component A @EJB means that for each component’s B instance a
new instance of component A will be created
It does not care about @SessionScoped and other scope annotations
May be used without CDI technology
@Inject (CDI) looks at the component’s A scope, takes corresponding context and:
if finds instance of component A, uses it
otherwise create a new instance of A, puts it to this context, and returns to component B
Introduction to EJB 30
Embeddable EJB containerpublic class DesktopApp {
public static void main(String args[]) {
EJBContainer ec = EJBContainer.createEJBContainer();
Context ctx = ec.getContext();
ByeEJB byeEjb =
(ByeEJB)ctx.lookup("java:global/bye/ByeEJB");
String msg = byeEjb.sayBye();
ec.close();
}
}
Introduction to EJB 31
Conclusions: EJB container provided middleware services1. Memory management – component pooling
2. Life-cycle management
3. Thread management
4. Asynchronous communication
5. Timer Service
6. Embeddable EJB container
7. Distribution transparency
8. Declarative transactions
9. Declarative security
Introduction to EJB 32