Java Reference
In-Depth Information
public class CacheSingletonBean {
private Map<Integer, String> myCache;
@EJB
MyLoggingBean loggingBean;
@PostConstruct
public void start(){
loggingBean.logInfo("Started!");
myCache = new HashMap<Integer, String>();
}
@AccessTimeout(value=30, unit=TimeUnit.SECONDS)
@Lock(LockType.WRITE)
public void addUser(Integer id, String name){
myCache.put(id, name);
}
@Lock(LockType.READ)
public String getName(Integer id){
return myCache.get(id);
}
}
The @AccessTimeout annotation can have different TimeUnit constants, such as
NANOSECONDS , MICROSECONDS , MILLISECONDS , and SECONDS . If no TimeUnit value
is given, the value is interpreted as milliseconds by default. You can also place this
annotation at the class level and apply it to all methods that don't explicitly dei ne an access
timeout annotation.
WHERE AND WHEN TO USE THE SINGLETON PATTERN
As a rule of thumb, heavy use of singletons may be a sign of misuse. You should use singletons
where it makes sense, such as caching frequently accessed but expensive‐to‐load data, sharing data
for global access, or using single point of contact purposes (such as logging).
Creating and caching unnecessary resources has a negative impact on memory, CPU resources,
and initial startup, so handle singletons with care when using them for caching data. However,
singletons can be quite handy and can be coni gured easily in a Java EE container. For serious
caching solutions, consider a framework such as the widely used Ehcache ( http://www.ehcache
.org/ ) or Apache's distributed caching system Java Caching System ( http://commons.apache
.org/proper/commons‐jcs/ ).
You can use a singleton to control access to back‐end systems that are not thread safe or have
licensing issues. Using the LockType.WRITE annotation on methods allows sequential access to
such systems in which multiple concurrent access would cause problems with performance or
licensing.
 
Search WWH ::




Custom Search