java - How to make this code thread-safe using double checked locking? -


this question has answer here:

single threaded version:

private final list<element> list = new arraylist<element>();  public element getelementat(int index) {      if (index >= list.size()) {         (int = list.size(); <= index; i++) {             list.add(createelement(i));         }     }      return list.get(index); } 

now trying make thread-safe version double checked locking:

import com.google.common.collect.immutablelist; import com.google.common.collect.immutablelist.builder;  ...  private volatile list<element> list = immutablelist.of();  public element getelementat(int index) {      if (index >= list.size()) {          synchronized (this) {             if (index >= list.size()) {                 builder<element> newlistbuilder = immutablelist.<element> builder();                 newlistbuilder.addall(list);                 (int = list.size(); <= index; i++) {                     newlistbuilder.add(createelement(i));                 }                  list = newlistbuilder.build();             }         }     }      return list.get(index); } 

is correct?

what doing more map/dictionary lookup. if consider list behaving map<integer, element> can use concurrent map's putifabsent method handle without blocking:

private final concurrentmap<integer, element> map =                 new concurrenthashmap<integer, element>();  public element getelementat(int index) {      if (index >= map.size()) {         (int = map.size(); <= index; i++) {             map.putifabsent(i, createelement());         }     }      return map.get(index); } 

this assumes there's no particular ordering requirements on elements returned createelement - though if that's case, you'd need tighter constraints on how they're created anyway.

chances though in reality stick synchronized block around method (and other accesses list). it's easy understand, , it's relatively fast. if getting elements isn't performance hotspot of code, wouldn't want "clever" shave off couple of nanoseconds.


Comments

Popular posts from this blog

c# - Send Image in Json : 400 Bad request -

jquery - Fancybox - apply a function to several elements -

An easy way to program an Android keyboard layout app -