2

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 ?

Andrea Ligios
  • 49,480
  • 26
  • 114
  • 243

2 Answers2

0

A "Single" Instance

A properly implemented Singleton will be constructed once within the context of your application, and once created will be re-used within the JVM. The Singleton pattern Wikipedia page says (in part),

In software engineering, the singleton pattern is a design pattern that restricts the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system.

tl;dr

Yes. A Singleton is a form of global variable, and thus there will only be one instance shared by all users.

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
0

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.

Andrea Ligios
  • 49,480
  • 26
  • 114
  • 243