12.07.2015 Views

Beginning Java EE 6 with GlassFish 3, Second Edition

Beginning Java EE 6 with GlassFish 3, Second Edition

Beginning Java EE 6 with GlassFish 3, Second Edition

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

CHAPTER 7 ■ SESSION BEANS AND THE TIMER SERVICE• @Lock(LockType.WRITE): A method associated <strong>with</strong> an exclusive lock will not allowconcurrent invocations until the method’s processing is completed. For example, if aclient C1 invokes a method <strong>with</strong> an exclusive lock, client C2 will not be able to invokethe method until C1 has finished.• @Lock(LockType.READ): A method associated <strong>with</strong> a shared lock will allow any numberof other concurrent invocations to the bean’s instance. For example, two clients, C1and C2, can access simultaneously a method <strong>with</strong> a shared lock.The @Lock annotation can be specified on the class, the methods, or both. Specifying on the classmeans that it applies to all methods. If the concurrency locking attribute is not specified, it is assumed tobe @Lock(WRITE) by default. The code in Listing 7-6 shows CacheEJB <strong>with</strong> a READ lock in the bean class.This implies that all methods will have READ concurrency except getFromCache(), which is overridden byWRITE.Listing 7-6. A Singleton Session Bean <strong>with</strong> CMC@Singleton@Lock(LockType.READ)public class CacheEJB {private Map cache = new HashMap();public void addToCache(Long id, Object object) {if (!cache.containsKey(id))cache.put(id, object);}public void removeFromCache(Long id) {if (cache.containsKey(id))cache.remove(id);}}@AccessTimeout(value = 20, unit = TimeUnit.SECONDS)@Lock(LockType.WRITE)public Object getFromCache(Long id) {if (cache.containsKey(id))return cache.get(id);elsereturn null;}In Listing 7-6, the getFromCache() method uses an @AccessTimeout annotation. When a concurrentaccess is blocked, a timeout can be specified to reject a request if the lock is not acquired <strong>with</strong>in a certaintime. If a getFromCache() invocation is locked for more than 20 seconds, the client will get aConcurrentAccessTimeoutException.212

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!