Java Reference
In-Depth Information
expensive to create the instance or it's guaranteed that you will need the bean from the start of the
application. To ensure that the instance is created at startup, use the @Startup annotation on the
class as shown in Listing 4‐8.
LISTING 4‐8: Invoking the singleton at startup
package com.devchronicles.singleton;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.PostConstruct;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import java.util.logging.Logger;
@Startup
@Singleton
public class CacheSingletonBean {
private Map<Integer, String> myCache;
@PostConstruct
public void start(){
Logger.getLogger("MyGlobalLogger").info("Started!");
myCache = new HashMap<Integer, String>();
}
public void addUser(Integer id, String name){
myCache.put(id, name);
}
public String getName(Integer id){
return myCache.get(id);
}
}
If you relaunch your server, the post construct method is invoked because the singleton is now
created at server startup. The logger should now receive the message Started!.
Determining Startup Order
This may bring up another question. What if the singleton you have just created depends on
another resource? How do you wait for the other resource to be ready? Although this may look
like a corner case, it dei nitely is not. Think about a singleton, which loads and caches some
messages from the database. This may look trivial, but even basic read‐only database access may
be dependent on other services. What if the connection pool is created by another singleton or,
better yet, what if the logging depends on another singleton? Java EE offers a simple annotation
to i x this situation. You can use the @DependsOn annotation and pass it the name of the bean on
which the class depends (see Listing 4‐9). Now you can easily determine the starting order of the
singletons.
 
Search WWH ::




Custom Search