views:

160

answers:

4
+7  Q: 

range lock in java

I have a large array to be accessed by multiple thread. Single lock is not efficient enough.Is there a range lock class in java or scala?

+1  A: 

Wrap the array inside a thread safe object that controls access. You could either manage the ranges yourself, or split the array up into ranges, each with their own lock, and reference it that way.

glowcoder
+5  A: 

Not in the standard libraries. ConcurrentHashMap does this though, internally representing the hash table as "segments" (16 of them by default) where each one is protected with a separate lock. Also, this thread asks the same question except about an ArrayList instead of an array. Although fruitless, it brings up alternatives if you are able to compromise on usage.

Update: Perhaps AtomicReferenceArray and friends would provide the efficiency you're looking for while at the same time "provid[ing] volatile access semantics to the elements of the array" (JCIP 15.3).

Brian Harris
+2  A: 

Generaly speaking, except if you have a really specific need in term of concurrency, you will find very optimized and convenient objects in the java.util.concurrent package of jdk.

I can suggest Brian Goetz's "Java Concurrency in Practice", a very good book explaining a lot of things about threading in java and java.util.concurrent package also.

Bruno Thomas
A: 

It really depends on your usage. If you actually mean ArrayList and not just array, then you will probably have to roll your own and stripe your locks, as ArrayLists can resize which can really screw up un-sychronized reads and writes.

If however, you actually mean an array, I'm not sure I understand what you mean. You don't need a lock, things will work fine without locks. Another thread may not see a change right away, but that isn't the end of the world.

runT1ME