-2

If you are using monitors in your concurrent system design, is this sufficient to prevent deadlock? I know that in Java there are many ways to cause deadlock, but few of these examples are actually to do with monitors (most use mutexes).

N. McA.
  • 4,796
  • 4
  • 35
  • 60
  • You can get deadlocks, and although hard to reproduce they will get you eventually (sometimes years later when you update a JVM, OS, or hardware) – Peter Lawrey May 03 '16 at 16:36

1 Answers1

-1

Deadlock can occur, but you are quite unlikely to have this happen by accident, I spent 10 minutes thinking up a horrible corner case.

In the following code, note that removing "synchronized" will cause it to terminate.

public class Foo implements Runnable {

    private Foo target;
    private int count;

    synchronized void go(int n) {
        try {
            if (n < 1) {
                System.out.println("Got to the bottom.");
            } else {
                Foo f = new Foo();
                f.target = this;
                f.count = n;
                Thread t = new Thread(f);
                t.start();
                t.join();
            }
        } catch (InterruptedException e) {
            // Demo
        }
    }

    @Override
    public void run() {
        target.go(count-1);    
    } 

    public static void main(String[] args) {
        new Foo().go(1);
    }
} 
N. McA.
  • 4,796
  • 4
  • 35
  • 60
  • This might demonstrate a deadlock, but it is a very poor example of writing multithreaded code. You're creating a `Foo` instance to start and join on a thread created from a new `Foo` instance within the origin `Foo` instance...It's quite upside down. – Sotirios Delimanolis May 03 '16 at 16:36
  • Basically, don't `start` a thread within your `Runnable` implementation if that thread is meant to run that `Runnable` implementation. – Sotirios Delimanolis May 03 '16 at 16:43
  • @SotiriosDelimanolis -> Yeah it's very bad code. It was just intended as an example to demonstrate that the monitor system, even ignoring considerations of signal/wait, is vulnerable to deadlock. I posted it because several high ranking results from google had *terrible* answers that instead demonstrated that mutexes could cause deadlock. – N. McA. May 03 '16 at 18:17