Presentation is loading. Please wait.

Presentation is loading. Please wait.

Session Beans and The Timer Service. Contents  Session Beans  The Timer Service.

Similar presentations


Presentation on theme: "Session Beans and The Timer Service. Contents  Session Beans  The Timer Service."— Presentation transcript:

1 Session Beans and The Timer Service

2 Contents  Session Beans  The Timer Service

3 1. Session Beans  Stateless Beans  Stateful Beans  Singletons  Session Bean Model  Asynchronous Calls

4 1.1.Stateless Beans Stateless beans are ideal when you need to implement a task that can be concluded with a single method call. Stateless session beans are pooled and shared by several clients.  For each stateless EJB, the container keeps a certain number of instances in memory (i.e., a pool) and shares them between clients.

5 Stateless beans have no client state, all instances are equivalent.  When a client invokes a method on a stateless bean, the container picks up an instance from the pool and assigns it to the client.  When the client request finishes, the instance returns to the pool to be reused. Only a small number of beans are needed to handle several clients.  The container doesn’t guarantee the same instance for the same client.

6 1.2.Stateful Beans Stateless beans provide business methods to their clients but don’t maintain a conversational state with them. Stateful session beans preserve conversational state.  They are useful for tasks that have to be done in several steps, each of which relies on the state maintained in a previous step.

7 When a client invokes a stateful session bean in the server, the EJB container needs to provide the same instance for each subsequent method invocation. Stateful beans cannot be reused by other clients.  The one-to-one correlation between a bean instance and a client.

8 Let’s take the example of a shopping cart in an e-commerce web site.  A customer logs on (his session starts), chooses a first item, adds it to his shopping cart, chooses a second item, and adds it to his cart. At the end, the customer checks out the books, pays for them, and logs out (the session ends). The shopping cart keeps the state of how many items the customer has chosen throughout the interaction (which can take some time, specifically the time of the client’s session).

9 Create an enterprise application  ShoppingCartEnterpriseApplication

10 Create the Item entity Create JDBC connection pool and data source in GlassFish applicarion server JDBC connection pool: shoopingcartPool Data source: shoppingcartDS Database: ShoppingCartDB

11

12 Write the ShoppingCartEJB stateful session bean

13 Override the equals method In the Item class.

14  @Remove Invoking the method causes the bean instance to be permanently removed from memory.  @StatefulTimeout Assigns a timeout value, which is the number of milliseconds the bean is permitted to remain idle (not receiving any client invocations) before being removed by the container. Alternatively, you can avoid these annotations and rely on the container automatically removing an instance when the client’s session ends or expires.

15 Write a unit test for the ShoppingCartEJB

16

17 Writing the Main class in Application Client Module

18 Writing a Main class of a stand- alone java client to access Remote EJB component 1. Add gf-client.jar (glassfish\modules) to the classpath 2. Add the jar file of ejb module to the classpath

19 1.3.Singletons A singleton bean is a session bean that is instantiated once per application. It ensures that only one instance of a class exists in the whole application and provides a global point of access to it. EJB 3.1 introduces the brand-new singleton session bean, which follows the singleton design pattern.  Once instantiated, the container makes sure there is only one instance of a singleton for the duration of the application.

20 By annotating a class with @Singleton, the container will make sure only one instance is created. An instance is shared between several clients. Singletons maintain their state between client invocations.

21 Initialization When a client class needs to access a method on a singleton session bean, the container makes sure to either instantiate it or use the one already living in the container. However, sometimes initializing a singleton can be time consuming. The first call to the bean will be expensive, and the first client will have to wait for initialization to be completed.  To avoid such latency, you can ask the container to initialize a singleton bean at startup.

22 If the @Startup annotation appears on the bean class, the container initializes it during the application startup, not when a client invokes it.

23 Chaining Singletons In some cases, when you have several singleton beans, explicit initialization ordering can be important. Imagine if the CacheEJB needs to store data that comes from another singleton bean (let’s say a CountryCodeEJB that returns all the ISO country codes).  The CountryCodeEJB then needs to be initialized before the CacheEJB.  Dependencies can exist between multiple singletons, and the @javax.ejb.DependsOn annotation is there to express it.

24

25 Concurrency There is only one instance of a singleton session bean shared by multiple clients. So concurrent access by clients is allowed and can be controlled with the @ConcurrencyManagement annotation in different ways:  Container-managed concurrency (CMC): The container controls concurrent access to the bean instance based on metadata (annotation or the XML equivalent).

26  Bean-managed concurrency (BMC): The container allows full concurrent access and defers the synchronization responsibility to the bean. If no concurrency management is specified, the CMC demarcation is used by default. A singleton bean can be designed to use either CMC or BMC, but not both.

27 Container-Managed Concurrency @Lock(READ)  The method can be concurrently accessed, or shared, with many clients. @Lock(WRITE)  The singleton session bean should be locked to other clients while a client is calling that method. Typically, the @Lock(WRITE) annotation is used when clients are modifying the state of the singleton. If the concurrency locking attribute is not specified, it is assumed to be @Lock(WRITE) by default.

28 The getState method can be accessed by many clients at the same time, because it is annotated with @Lock(READ). When the setState method is called, however, all the methods in ExampleSingletonBean will be locked to other clients because setState is annotated with @Lock(WRITE).

29 Using Class- and Method-Level @Lock Annotations in a Singleton Session Bean

30 If a method is of locking type WRITE, client access to all the singleton's methods are blocked until the current client finishes its method call, or an access timeout occurs.  When an access timeout occurs, the EJB container throws a javax.ejb.ConcurrentAccessTimeoutException. The javax.ejb.AccessTimeout annotation is used to specify the number of milliseconds before an access timeout occurs.  The @AccessTimeout annotation can be applied to both @Lock(READ) and @Lock(WRITE) methods.

31 Bean-Managed Concurrency With BMC demarcation, the container allows full concurrent access to the singleton bean instance. You are then responsible for guarding its state against synchronization errors due to concurrent access. In this case, you are allowed to use Java synchronization primitives such as synchronized and volatile.

32 1.4.Session Bean Model Interfaces and Bean Class  Business interfaces: These interfaces contain the declaration of business methods that are visible to the client and implemented by the bean class. A session bean can have local interfaces, remote interfaces, or no interface at all (a no-interface view with local access only).  A bean class: The bean class contains the business method implementation and can implement zero or several business interfaces. The session bean must be annotated with @Stateless, @Stateful, or @Singleton depending on its type.

33 Session beans have several types of interfaces

34 Remote, Local, and No-Interface Views  Depending from where a client invokes a session bean, the bean class will have to implement remote or local interfaces, or no interface at all.  If your architecture has clients residing outside the EJB container’s JVM instance, they must use a remote interface. this applies for clients running in a separate JVM (e.g., a rich client), in an application client container (ACC), or in an external web or EJB container. In this case, clients will have to invoke session bean methods through Remote Method Invocation (RMI).

35  You can use local invocation when the bean and the client are running in the same JVM. That can be an EJB invoking another EJB or a web component (servlet, JSF) running in a web container in the same JVM.

36  The no-interface view is a variation of the local view that exposes all public business methods of the bean class locally without the use of a separate business interface. @Remote  Denotes a remote business interface. Method parameters are passed by value and need to be serializable as part of the RMI protocol. @Local  Denotes a local business interface. Method parameters are passed by reference from the client to the bean.

37

38

39 Bean Class  The class must be annotated with @Stateless, @Stateful, @Singleton, or the XML equivalent in a deployment descriptor.  It must implement the methods of its interfaces, if any.  The class must be defined as public, and must not be final or abstract.  The class must have a public no-arg constructor that the container will use to create instances.  The class must not define the finalize() method.  Business method names must not start with ejb, and they cannot be final or static.  The argument and return value of a remote method must be legal RMI types.

40 Client View  Session beans had no interface For a client to invoke a session bean’s no-interface view, it needs to obtain a reference to the bean class itself.

41  If the session bean implements several interfaces, the client has to specify which one it wants a reference to. The client can invoke the EJB through either its local or remote interface, but not through the no-interface view anymore.

42  If the bean exposes at least one interface, it needs to specify that it exposes a no-interface view by using the @LocalBean annotation on the bean class. A client can now invoke the bean through its local, remote, and no-interface view.

43 Global JNDI Access  java:global[/ ]/ / [! ]  To illustrate this naming convention, let’s take the example of ItemEJB. ItemEJB is the and is packaged in the cdbookstore.jar (the ). The EJB has a remote interface and a no-interface view (using the @LocalBean annotation). Once deployed, the container will create the following JNDI names:

44

45  If the bean exposes only one client interface (or has only a no-interface view), the container registers a JNDI entry for that view with the following syntax : java:global[/ ]/ /

46 Session Context  Beans can use container services in code such as explicitly marking a transaction to be rolled back. Using SessionContext interface A session bean can have access to its environment context by injecting a reference of SessionContext with a @Resource annotation.

47  Some Methods of the SessionContext Interface

48 Environment Naming Context  Environment entries (parameters) are specified in the deployment descriptor and are accessible via dependency injection (or via JNDI). They support the following Java types: String, Character, Byte, Short, Integer, Long, Boolean, Double, and Float.

49 A Stateless Session Bean Converting Prices to Euros

50 1.5.Asynchronous Calls By default, session bean invocations through remote, local, and no-interface views are synchronous:  A client invokes a method, and it gets blocked for the duration of the invocation until the processing has completed, the result is returned, and the client can carry on its work.

51 But asynchronous processing is a common requirement in many applications handling long running tasks.  For example, printing an order can be a very long task depending on whether the printer is online, dozens of documents are already waiting to be printed in the printer’s spool, …. When a client calls a method to print a document, it wants to trigger a fire-and-forget process that will print the document so the client can carry on its processing.  Since EJB 3.1, you can call methods asynchronously simply by annotating a session bean method with @javax.ejb.Asynchronous

52  An OrderEJB That Declares Two Asynchronous Methods When a client invokes either the printOrder() or sendEmailOrderComplete() method, the container returns control to the client immediately and continues processing the invocation on a separate thread of execution.

53  An asynchronous method can return void as well as a java.util.concurrent.Future object, where V represents the result value.  Future objects allow you to obtain a return value from a method executed in a separate thread. The client can then use the Future API to get the result or even cancel the call.

54 @Singleton @Asynchronous public class AsyncBean { @Asynchronous //this line can be omitted public void ignoreResult(int a, int b) { // the client doesn't care what happens here } @Asynchronous //this line can be omitted public Future longProcessing(int a, int b) { return new AsyncResult (a * b); } asyncBean.ignoreResult(0, 0); // fire and forget System.out.println("Proceed without waiting for the async method result."); Future futureResult = asyncBean.longProcessing(8, 9); System.out.println("Proceed to other tasks and check async method result later."); Integer intResult = futureResult.get(); System.out.println("The prior async method returned " + intResult);

55 2. The Timer Service The EJB timer service is a container service that allows EJBs to be registered for callback invocation.  The container keeps a record of all the timers, and invokes the appropriate bean instance method when a timer has expired.  Stateless beans, singletons, and MDBs can be registered by the timer service, but stateful beans can’t and shouldn’t use the scheduling API.

56 Timers can be created automatically by the container at deployment time if the bean has methods annotated with the @Schedule annotation. But timers can also be created programmatically and must provide one callback method annotated with the @Timeout annotation.

57 Timers are intended for long-lived business processes and are by default persistent.  This means they survive server shutdowns, and once the server starts again, the timers are executed as if no shutdown had happened. Optionally, you can specify timers to be nonpersistent.

58 Calendar-Based Expression Attributes of a Calendar-Based Expression

59 Forms of Expression

60

61

62 Automatic Timer Creation  Timers can be created automatically by the container at deployment time based on metadata.  The container creates a timer for each method annotated with @javax.ejb.Schedule or @Schedules. By default, each @Schedule annotation corresponds to a single persistent timer, but you can also define nonpersistent timers.

63 A timer is created that will call this method every first day of the month at 5:30 a.m. Two timers : one every day at 2 a.m., and another one every Wednesday at 2 p.m. A nonpersistent timer is created and will refresh the cache every 10 minutes.

64 Programmatic Timer Creation  Read the book, pp.220-222

65 Reference Antonio Goncalves, Beginning Java EE 6 Platform with GlassFish 3, Chapter 7, Apress 2009


Download ppt "Session Beans and The Timer Service. Contents  Session Beans  The Timer Service."

Similar presentations


Ads by Google