Thread Safety of ServletContext objects

后端 未结 5 1482
余生分开走
余生分开走 2020-12-06 13:15

I am storing a HashMap object in my ServletContext. But Multiple Request thread are reading and Modifying this HashMap.

As i belive the ServletContext objects are sh

5条回答
  •  情深已故
    2020-12-06 13:31

    The best way in a multithreaded environment is to use java.util.concurrent.ConcurrentHashMap. It is designed specifically in a way that allows you to read and modify it without any ConcurrentModificationException. Nevertheless, in case of iteration you should synchronize on its instance, in order to always get the predicatble results.

    Synchronizing on the context gives you a lot of overhead, if you retrieve anything else from there in a multithreaded manner. So ConcurrentHashMap is a better solution.

    You can read about it here:

    http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ConcurrentHashMap.html

    A hash table supporting full concurrency of retrievals and adjustable expected concurrency for updates. Retrieval operations (including get) generally do not block, so may overlap with update operations (including put and remove).

提交回复
热议问题