Skip to main content

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

Popular posts from this blog

AirBnB Infographic Journey to IPO

  Full Post at  https://techpomelo.com/2020/10/infographics-airbnb-milestone-journey-to-ipo/

8 common methods for server performance optimization

  1. Use an in-memory database In-memory database is actually a database that puts data in memory and operates directly. Compared with the disk, the data read and write speed of the memory is several orders of magnitude higher. Saving the data in the memory can greatly improve the performance of the application compared to accessing it from the disk. The memory database abandoned the traditional way of disk data management, redesigned the architecture based on all data in memory, and made corresponding improvements in data caching, fast algorithms, and parallel operations, so the data processing speed is faster than that of traditional databases. Data processing speed is much faster.       But the problem of security can be said to be the biggest flaw in the memory database. Because the memory itself has the natural defect of power loss, when we use the memory database, we usually need to take some protection mechanisms for the data on the memory in advance, such...