0

In the java web project, I have a set of java bean to cache, so, I use java.lang.HashMap to store those objects, everytime, client get those object from this map when make a http request. But sometime, this map needs to update a few objects, in the multi-threading environment, I worry about that when one thread updating the object of map, another thread make a get operation to this map, just like this:

Thread-1:

map.put("user:1001", userObject);

Thread-2:

User userObject = map.get("user:1001");

I don't want to use synchronized strategy, so what is the good way to update a map when a client may get the value from?

CandleCoder
  • 1,387
  • 4
  • 21
  • 45
Leo Chu
  • 83
  • 1
  • 1
  • 6
  • 2
    Why don't you want to synchronize things? – Maroun Jan 03 '16 at 13:11
  • [This SO article](http://stackoverflow.com/questions/1291836/concurrenthashmap-vs-synchronized-hashmap) might be of use to you. It sounds like you want reads and writes to the `HashMap` to happen atomically and in a thread-safe manner. – Tim Biegeleisen Jan 03 '16 at 13:12
  • 2
    Consider `ConcurrentHashMap` – coolguy Jan 03 '16 at 13:18
  • Because there is a large amount of clients request data from this map, so, make synchronized get will increase the time of get operation, that's what i don't want. – Leo Chu Jan 03 '16 at 13:26
  • 1
    Use a ConcurrentHashMap as suggested by coolguy. The read operations won't be locked with this. So this won't effect much on get. Only write operations are locked. – Harinder Jan 03 '16 at 13:31
  • Thanks for everybody, I found this explain what i worry about:http://stackoverflow.com/questions/22562165/best-way-to-synchronize-infrequently-updated-hashmap – Leo Chu Jan 03 '16 at 13:47

0 Answers0