开发者

Is ConcurrentHashMap a reliable choice to use inside Servlet?

I need to map objects inside Servlet. Is ConcurrentHashMap a reliable choice to use? Will all requests get requested object from map or wil开发者_如何学编程l there be failures?

public class MyServlet extends HttpServlet {

    private Map<String, Object> map = new ConcurrentHashMap<String, Object>();

    public void doGet(HttpServletRequest request, HttpServletResponse response) {
        // use map
        map.get("myObjectName");
    }

}


The purpose of a ConcurrentHashMap is to allow retrieval without locking. It is suitable for multi-threaded programs that have lot of reads and very few writes.

You wrote

Objects are not modifided after servlet init. – newbie

If by that you mean that the map does not change after servlet initialization, then you don't need a ConcurrentHashMap at all. You can use plain old HashMap. Even better would be to convert it to a non-modifiable map by using Collections.unmodifiableMap.


Since the map is only initialized at startup, you should consider using Guava's ImmutableMap:

private static final ImmutableMap<String, Object> MY_MAP = ImmutableMap
       .<String, Object>builder()
       .put("asdf", myObj1)
       .put("qwerty", myObj2)
       .build();

The Builder is used to pre-populate the map with the desired values, after which calling build() returns the map. From then on it is immutable, making it thread safe.

You can also use the of factory methods for a limited number of key-value pairs:

private static final ImmutableMap<String, Object> MY_MAP = ImmutableMap.of(
        "asdf", myObj1,
        "qwerty", myObj2
);


The answer depends on whether the rest of the method alters the map or not.

There's no guarantee that changes to the map will be ACID as written.

It's usually a bad idea to have shared state like this in a servlet. They're for handling HTTP requests. Better to move that functionality off to a service that will do the work.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜