简体   繁体   中英

Will a singleton created in struts action persist?

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 ?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM