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/

Defination of the essential properties of operating systems

Define the essential properties of the following types of operating sys-tems:  Batch  Interactive  Time sharing  Real time  Network  Parallel  Distributed  Clustered  Handheld ANSWERS: a. Batch processing:-   Jobs with similar needs are batched together and run through the computer as a group by an operator or automatic job sequencer. Performance is increased by attempting to keep CPU and I/O devices busy at all times through buffering, off-line operation, spooling, and multi-programming. Batch is good for executing large jobs that need little interaction; it can be submitted and picked up later. b. Interactive System:-   This system is composed of many short transactions where the results of the next transaction may be unpredictable. Response time needs to be short (seconds) since the user submits and waits for the result. c. Time sharing:-   This systems uses CPU scheduling and multipro-gramming to provide econ...