What is Lock contention in multithreading in Java? What are the techniques to reduce Lock contention in Java? What technique can be used in following code to reduce Lock contention in Java?
What is Lock contention in multithreading?
Lock contention is the situation when one thread is waiting for a lock/object that being held by another thread.
The waiting thread cannot use this object until the other thread releases the lock on that object.
It is also known as Thread contention.
Ideally locks reduce the thread contention. Without locks, multiple threads can operate on same object and cause undesirable behavior.
If locking is implemented correctly it reduces the occurrence of contention between multiple threads.
What are the techniques to reduce Lock contention?
There are following main techniques to reduce Lock contention:
1. Reduce the scope of lock.
2. Reduce object pooling.
3. Reduce the number of times a certain lock can be acquired.
4. Avoid synchronization at unnecessary places.
5. Implement hardware supported Optimistic locking in place of synchronization.
What technique can be used in following code to reduce Lock contention?
synchronized (map) {
Random r = new Random();
Integer value = Integer.valueOf(42);
String key = r.nextString(5);
map.put(key, value);
} T
he code uses Random() to get a random string and it also used
Integer to convert 42 in an object. Since these lines of code are
specific to this thread, these can be moved out of Synchronization
block.
Random r = new Random();
Integer value = Integer.valueOf(42);
String key = r.nextString(5);
synchronized (map) {
map.put(key, value);
}
Comments
Post a Comment