Deadlock and livelock in Java

Deadlock

Deadlock is a phenomenon in which all threads are in a waiting mode. Occurs when states are reached:

  1. mutual exclusion: at least one resource is busy in indivisible mode and therefore only one thread can use the resource at any given time.
  2. holds and waits: a thread is holding at least one resource and is requesting additional resources that are held by other threads.
  3. lack of precleaning: the operating system does not reassign resources: if they are already occupied, they should be given to the holding threads immediately.
  4. circular wait: a thread is waiting for the resource to be released by another thread, which in turn is waiting for the resource locked by the first thread to be released.

The simplest way to avoid deadlocks is to avoid waiting loops. This can be achieved by fetching shared resource monitors in a specific order and freeing them in reverse order.

Livelock

Livelock is a type of deadlock in which multiple threads do useless work, getting caught up in a loop while trying to get some resources. Moreover, their states are constantly changing depending on each other. No actual error occurs, but the system efficiency drops to 0. Often occurs as a result of attempts to avoid deadlocks.

A real example of a livelock is when two people meet in a narrow corridor and each, trying to be polite, steps aside, and so they endlessly move from side to side, absolutely not moving in the direction they need.

How to check if a thread is holding a specific resource?

The Thread.holdsLock(lock) method returns true when the current thread is holding the monitor on a specific object.

What object is synchronized on when a static synchronized method is called?

A synchronized static method does not have access to this, but it does have access to an object of the Class class, it is present in a single instance and it is he who acts as a monitor for synchronizing static methods. Thus, the following construction:

public class SomeClass {

    public static synchronized void someMethod() {
        //code
    }
}

is equivalent to this:

public class SomeClass {

    public static void someMethod(){
        synchronized(SomeClass.class){
            //code
        }
    }
}


Read also:


Comments

Popular posts from this blog

Methods for reading XML in Java

XML, well-formed XML and valid XML

ArrayList and LinkedList in Java, memory usage and speed