If I instantiate a Singleton class in a Struts action, will it be persistent for other request firing up that action ?
I mean, if I'm in a Struts action code and I write:
Singleton object = Singleton.getInstance();
will the object exist when another user fires up the same or another action requiring that object ?
I get your doubt:
since Struts2 Actions are ThreadLocal
, and hence every action, on every request, creates an instance of its object, will a Singleton behave correctly ?
From your code it seems you are referring to the pre-1.5* Singleton:
public class Singleton {
private static final Singleton INSTANCE = new Singleton();
private Singleton() {}
public static Singleton getInstance() {
return INSTANCE;
}
}
The answer is yes:
private static final Singleton INSTANCE = new Singleton();
since static
"wins" over ThreadLocal
, and makes it unique (instantiated once, then shared).
*Note that if you are on Java EE >= 6, there are many ways to handle Singletons better than this, with CDI, EJB3, etc... eg @Singleton
EJB or @Singleton
injections.