Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 876
user398384 Avatar asked Jul 21 '10 19:07

user398384


People also ask

What are locks in Java?

Simply put, a lock is a more flexible and sophisticated thread synchronization mechanism than the standard synchronized block. The Lock interface has been around since Java 1.5. It's defined inside the java. util. concurrent.

What are locks in multithreading?

A lock may be a tool for controlling access to a shared resource by multiple threads. Commonly, a lock provides exclusive access to a shared resource: just one thread at a time can acquire the lock and everyone accesses to the shared resource requires that the lock be acquired first.

What is difference between lock and synchronization in Java?

Major difference between lock and synchronized: with locks, you can release and acquire the locks in any order. with synchronized, you can release the locks only in the order it was acquired.


2 Answers

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).

like image 198
Brian Harris Avatar answered Oct 13 '22 19:10

Brian Harris


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.

like image 20
Bruno Thomas Avatar answered Oct 13 '22 18:10

Bruno Thomas