2

I am currently developing a Java web application that exposes a web service interface. The class definition of my web service is as follows:

@WebService()
public class ETL_WS {
    private String TOMCAT_TEMP_DIR;
    private final int BUFFER_SIZE = 10000000;
    private ConcurrentHashMap myMap;
    private String dbTable = "user_preferences";

    public ETL_WS() {
        Context context = null;
        try {
            context = (Context) new InitialContext().lookup("java:comp/env");
            this.TOMCAT_TEMP_DIR = (String) context.lookup("FILE_UPLOAD_TEMP_DIR");
        }catch(NamingException e) {
        System.err.println(e.getMessage());
    }

    public long getCouponMapCreationTime() {
        return couponMap.getCreationTime();
    }

}

Due to the fact that I need all the requests to see the same ConcurrentHashMap myMap instance, I would like to know what is the lifetime of a web service object. To be specific, I know that it is initialized at the first client request. But, will all the clients see the same instance of the myMap object? If not, how is this possible?

Thank you for your time.

informatik01
  • 16,038
  • 10
  • 74
  • 104
nick.katsip
  • 868
  • 3
  • 12
  • 32

2 Answers2

3

Short answer: No, you have no control over how many instances of this class will be created by the application server. The only sure thing is that at least one object will be instantiated before the first request. Typically, application servers create one instance per worker thread, which means tens of object of the same class.

However, it's possible to have common data among these instances, the most simple solution is to use static member variables. Static members are guaranteed to be unique among every objects, since they belong to the class.

@WebService()
public class ETL_WS {
    // ...
    private static ConcurrentHashMap myMap;
    // ...
}
buc
  • 6,268
  • 1
  • 34
  • 51
1

One way that I can think of will be to maintain this in a singleton behind the Webservice, this way the WS lifecycle does not really matter (It is a singleton - but the purpose of the WS interface is to simply get the request in, it would be better to encapsulate the core logic of the application behind it in a service).

Biju Kunjummen
  • 49,138
  • 14
  • 112
  • 125
  • What do you mean "behind the Webservice"? I think that a singleton member class could do the trick. Can you give me an example of encapsulating the core logic of the application behind the web service? Thank you for your quick answer. – nick.katsip Jun 19 '12 at 20:14