Two threads are waiting for each other, not able to resolve

There are two methods one pushes the message to arraylist and other retrieves the messages from the arraylist. Both methods are synchronized. I have created two threads,one to push the message into arraylist and other to retrieve. Two threads are in a deadlock situation.How to resolve it

Below is the code to push and display messages

public class FetchCurrentTime {

    static final int MAXMESSAGE = 5;
    private List<String> messages = new ArrayList<String>();

    public synchronized void putTime(){
        while(messages.size() != MAXMESSAGE){
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            Calendar cal = Calendar.getInstance();
            messages.add(dateFormat.format(cal.getTime()).toString());
        }
        notify();

    }

    public synchronized String getTime(){
        String message= "Unable to fetch time";
        try {
            wait();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        if(!message.isEmpty()){
        message = messages.remove(messages.size()-1);
        }
        notify();
        return message;
    }

}

Below is the Producer and consumer code

public class ProduceTime extends Thread {
    FetchCurrentTime fc ;

    public ProduceTime(FetchCurrentTime fc) {
            this.fc = fc;
    }

    @Override
    public void run() {
        fc.putTime();
    }

}


public class ConsumeTime extends Thread {
    FetchCurrentTime fc ;
    public ConsumeTime(FetchCurrentTime fc) {
        this.fc = fc;
    }

    @Override
    public void run() {
        while (true) {
            String time = fc.getTime();
            System.out.println(time);
        }
    }

}

Here is the code to test.

public class GetDate {

    public static void main(String[] args) throws InterruptedException {
        FetchCurrentTime fc = new FetchCurrentTime();
        ProduceTime p = new ProduceTime(fc);
        ConsumeTime c = new ConsumeTime(fc);

        Thread t1 = new Thread(p);
        Thread t2 = new Thread(c);

        t1.start();
        t2.start();
    }

}

I see that the issue is with when wait() is being called in getTime() and putTime(), as both wait for the other to notify; which never occurs. Also, there is a typo in getTime(), should be messages.isEmpty() (list) and not message.isEmpty() (String)

You could give this code a try. Note that it runs forever, so you will need to handle the termination conditions.

public synchronized void putTime() {

    while (true) {  // To ensure list contains 5 elements at any point of time before removal
        if (messages.size() >= MAXMESSAGE) {
            try {
                wait(); // wait issued only when list is full
            } catch(InterruptedException e) {
                e.printStackTrace();
            }
        }

        while (messages.size() < MAXMESSAGE) {
            DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            Calendar cal = Calendar.getInstance();
            messages.add(dateFormat.format(cal.getTime()).toString());
        }

        notify();   // notify getTime() to resume execution
    }
}

public synchronized String getTime() {
    String message = "Unable to fetch time";

    try {
        Thread.sleep(100);  // adding delay to help see the output

        if (messages.isEmpty()) {
            wait(); // wait for putTime() to add messages to the list
        }

        if (!messages.isEmpty()) {
            message = messages.remove(messages.size() - 1);
            notify();   // notifies putTime() to add a message to the list; helps keep count to 5
        }
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    return message;
}

That said, it is recommended to use the advanced Thread constructs which help achieve the same (much easier) with a better throughput.

Hope this helps :)

Understanding Deadlock, Livelock and Starvation with Code , Similarly, thread 2 also has to wait because account 3 doesn't have sufficient fund. Both threads block each other forever, deadlock occurs and the program hangs. They keep repeating a particular code so the program is unable to a hostage and he asks for ransom in order to release the hostage. Deadlock describes a situation where two or more threads are blocked forever, waiting for each other. Deadlock occurs when multiple threads need the same locks but obtain them in different order. A Java multithreaded program may suffer from the deadlock condition because the synchronized keyword causes the executing thread to block while

please find the below issues in your code.

  1. Provide initial time for producer to generate number, hence include Thread.sleep(100) in consumer thread.
  2. Threads have to wait() at below criteria. a). Consumer Thread - wait() only if array.size() is zero. b). Producer Thread - wait() only if array.size() >= MAX_SIZE.

Note - use notifyAll instead of notify.

Reading 23: Locks and Synchronization, The correctness of a concurrent program should not depend on accidents of timing. release relinquishes ownership of the lock, allowing another thread to take B are synchronized, but another cash machine C is able to run independently on possible to get into a a situation where two threads are waiting for each other� The answer is simple — when two or more threads are waiting for each other to release the resource they need (lock) and get stuck for infinite time, the situation is called deadlock. It will only

There are lots of ways to solve this problem. A deadlock can occur any time where there are two or more locks acquired by two threads in different orders. The ordering is a critical part.

E.g. if one thread can acquire the put lock, and the other acquires the get lock, then vice versa, there's a dead lock. If each thread always acquires the get lock first, then the put lock, and releases the put lock before releasing the get lock, then a deadlock is impossible.

To resolve, make the locks explicit (e.g.: synchronized(lockObject){ /* the code */ }), and either always acquire the locks in order, or only use one lock.

Another solution would be to use an actor framework like Akka. An actor abstracts away the locking, and is particularly suitable to sending and receiving messages. With an actor, there's a "mailbox" with synchronized access to add messages from other threads, but the actor itself processes messages serially in its one thread.

THI02-J. Notify all waiting threads rather than a single , The notifyAll() method wakes up all threads waiting on an object lock and allows Presumably, the other threads will resume waiting. The notify() method wakes up only one thread, with no guarantee regarding which specific thread is notified. a single thread waiting on a condition, and that thread is not able to resolve the � The client process can create separate threads; each thread can fetch a different part of the file from one of the mirror servers. This can help reduce downtime. Of course, there is a single network link being shared by all threads. This link can become a bottleneck as the number of threads becomes very large.

Locks, Blocks, and Deadlocks, no other thread of control can read that object (in the case of an exclusive lock), and JE applications support both exclusive and non-exclusive locks. able to achieve repeatable reads; by default, the cursor's transaction holds a read lock entire thread of control must pause until the lock request is in some way resolved. As I didn’t know this technique, it was all like: load template – wait – load json – wait – work with the data – show them. This really helps. In my project, I don’t know if the source I’m trying to get with ajax does exist or not, I can’t rely on “then” callback. It fails if it can’t download the source.

[PDF] Deadlocks and Starvation, On the other hand, writers would not wait indefinitely as long as ready threads are served in order. Why? Example 2: Page 2. Thread A. Thread B. A thread will need to wait for its turn only when two threads call the increment () method on the same instance of SynchronizedCounter. Actually, Saying not possible is wrong. You can obviously call the increment method from multiple threads, but they will enter the increment method one-by-one because of the synchronized keyword.

Deadlock in Java Multithreading, It is not recommended to run the above program with online IDE. Now, both threads are in wait state, waiting for each other to release locks. Using the output of these kb commands, you can find the deadlock: two threads that are each waiting on a lock held by the other thread. In rare cases, a deadlock could be caused by more than two threads holding locks in a circular pattern, but most deadlocks involve only two threads. Here is an illustration of this procedure.

Comments
  • Describe in words what your putTime is doing.
  • Are you testing out the wait and notify methods? Modern Java code does not use notify and wait. There exists higher order classes and methods for working in a multithreaded application.
  • @SotiriosDelimanolis putTime gets the current time and adds the time to arraylist of string. I made putTime and getTime methods synchronzied so that while putTime is inserting messages into arraylist, getTime should not retrieve the message from arraylist and display it
  • Describe the code, specifically.
  • Your producer and consumer don't share the array list. There's nothing to synchronize. Also, the error is quite obvious. What Sotirios means is: When you describe your functions to yourself, you will find the error. Another hint: Who is calling notify()?
  • If you're going to down-vote, might want to let me know why.
  • You're talking about deadlocks in general but don't explain how it applies to their question at all. Then you bring in Akka for some reason. You're completely missing the point. The comments on the question do a better job describing the issues. You may want to include them in your answer.
  • The specific question was "Two threads are in a deadlock situation.How to resolve it." Either acquiring locks in order, or using akka, will remove deadlocks. I answered the question as it was written, I'm not going to write his code for him.
  • Read between the lines. These two threads are in a deadlock situation. How do I resolve *this* situation. To make your answer useful, describe what that situation is, why there is a deadlock in this situation, and how they could resolve it. You don't need to write any code. Otherwise, just flag (or vote once you have enough reputation) to close as one of the thousands of duplicates about deadlocks that are out there.