How to access a share from a web service?

I read that in Java EE, the web service will spawn a thread for each request, so I don't need to perform thread blocking operations (like database queries).

How can I correctly access a shared resource from such a thread-sent method?

eg. if I have a SessionManager that contains a map of User objects and a loginUser() method to allow logins outside the JSF context, how can I prevent race conditions? Am I just using mutexes, or is JavaEE providing a solution to this problem?

0
source share
2 answers

Java EE does not provide you with any solution for competing resources over your own resources; but Java does.

In your case, using ConcurrentHashMap can solve most of your problems. A ConcurrentHashMap will protect you from cases where two threads are updating the Map exactly the same time (which in HashMap will most likely throw an exception). It offers you the same methods from the Map interface as HashMap , as well as some useful methods from the ConcurrentMap interface (for example, replace and putIfAbsent ). For most needs, this option is sufficient.

Having said that sometimes you might need to use the synchronized , even if you use ConcurrentHashMap . For example, consider the case where you want to put two elements in a Map , but it is extremely important for you that although the current stream returns two put s, no other stream will get or put from the map. In other words, ConcurrentHashMap only isolates access for each call individually; for cases where you need isolation to enable multiple calls, use synchronized .

EDIT after the comment by @Arjan: if you are using JavaEE 6.0, you can use @Singleton in combination with @Lock to achieve a similar effect.

+1
source

If you need to use a map, you can use Concuurent HashMap .. Java will not have to deal with something that you want to manually create a similar web server that will hold pairs of user key values ​​and something like sessionId after logging in . Usually the server can do this.

In any case, this is not a problem. This ConcurrentHashMap is ideal for these situations, it is thread safe, and it has better performance than HashTable (they work differently)

HashTable blocks the map. ConcurrentHashMap blocks the evrey element itself. Thus, 2 threads can use the card together if they do not touch the same nodes.

You should read the following: http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ConcurrentHashMap.html

Hope that helps

+1
source

All Articles