Singleton Object in Java Web service

A JAX-WS web service is by itself a Singleton. This means that all the request will be handled using a single web service instance (like a Servlet).

So, any member of the class will be ‘shared’ between all the request. In your case, you do not need to make your members (i.e. couponMap) an static attributes.

Conclusion: Don’t worry, all your threads (request) will be accessing the same ‘couponMap’. Because you don’t need the getCouponMapCreationTime anymore, I think that you can eliminate the SingletonMap abstraction and use directly a Map in your web service class.

But I have something very important to add. If several threads (request) will be accessing your Map you have to make it thread-safe!!! There are a lot of way to do this, but I will give an idea: Use a ConcurrentHashMap instead of a HashMap. This will make all your get(), put(), remove() operations thread-safe! If you need a larger scope you can use synchronized blocks, but please avoid synchronize methods because the scoop is too large and always synchronize over this object.

Leave a Comment