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?
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.
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.
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.
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With