Pages

Deadlock in java?

 What is a deadlock in java?



A 𝐝𝐞𝐚𝐝𝐥𝐨𝐜𝐤 occurs when two or more threads wait "forever" for a lock or resource held by another of the threads.

When one thread is waiting for an object lock that has been acquired by another thread, while the second thread is waiting for an object lock that has been gained by the first thread, a deadlock will result. Deadlock is the term used to describe the situation since both threads are awaiting one another's release of the lock.

We can prevent deadlocks in our programming in three different ways:

1) Prevent the requirement of obtaining numerous locks for a thread.

2) To prevent any cyclic dependency in lock acquisition, we should ensure that each thread acquires the locks in the same order if you absolutely require several locks in the same thread.

3) Use timed lock attempts, such as the tryLock() method in the java.util.concurrent.locks.Lock interface, to prevent threads from becoming stuck indefinitely if they are unable to obtain a lock.



****************************************************

Find another must-read post.


No comments:

Post a Comment