View Javadoc
1   package ejava.examples.ejbsessionbank.ejb;
2   
3   import javax.annotation.PostConstruct;
4   import javax.ejb.AccessTimeout;
5   import javax.ejb.ConcurrencyManagement;
6   import javax.ejb.ConcurrencyManagementType;
7   import javax.ejb.Lock;
8   import javax.ejb.LockType;
9   import javax.ejb.Singleton;
10  import javax.ejb.Startup;
11  
12  import org.slf4j.Logger;
13  import org.slf4j.LoggerFactory;
14  
15  /**
16   * This class provides an example of a Singleton EJB. The container will
17   * instantiate only one instance of this class and manage concurrent
18   * access to the instance.
19   */
20  @Singleton
21  //used to cause the singleton to be initialized during server startup --
22  //otherwise it would be on demand
23  @Startup
24  //tells the container to manage concurrent access. Alternately we could use 
25  //BEAN and standard Java concurrency managaement mechanisms
26  @ConcurrencyManagement(ConcurrencyManagementType.CONTAINER)
27  //establish an access timeout either at class or method level
28  @AccessTimeout(value=3000)
29  public class StatsEJB implements StatsLocal, StatsRemote {
30  	static final Logger log = LoggerFactory.getLogger(StatsEJB.class);
31  	private int delta;
32  	private int total;
33  	
34  	@PostConstruct
35  	public void init() {
36  		log.info("*** StatsEJB ***");
37  	}
38  
39  	/**
40  	 * An example of a write method that the container will protect against
41  	 * other write and readers.
42  	 */
43  	@Override
44  	@Lock(LockType.WRITE)
45  	public void open() {
46  		this.delta += 1;
47  		this.total += 1;
48  		log.debug(String.format("open: stats=%d, total=%d", delta, total));
49  	}
50  	
51  	@Override
52  	@Lock(LockType.WRITE)
53  	public void close() {
54  		this.delta -= 1;
55  		this.total += 1;
56  		log.debug(String.format("close: stats=%d, total=%d", delta, total));
57  	}	
58  	
59  	/**
60  	 * An example read method that the container will protect from other
61  	 * write methods, but allow concurrent read access.
62  	 */
63  	@Override
64  	@Lock(LockType.READ)
65  	public int getTotal() {
66  		log.debug(String.format("getTotal: stats=%d, total=%d", delta, total));
67  		return total;
68  	}
69  
70  	@Override
71  	@Lock(LockType.READ)
72  	public int getDelta() {
73  		log.debug(String.format("getDelta: stats=%d, total=%d", delta, total));
74  		return delta;
75  	}
76  	
77  	@Override
78  	@Lock(LockType.WRITE)
79  	public void reset() {
80  		delta=0;
81  		total=0;
82  		log.debug(String.format("reset: stats=%d, total=%d", delta, total));
83  	}
84  }