Question

After hours of reading i am still struggling to understand what the monitor object exactly does.

A demo to show what i mean:

public class Demo {

    public static Bathroom bathroom = new Bathroom();

    public static Kitchen kitchen = new Kitchen();

    public static void main(String[] args) {
        (new Thread(new Roommate("bob"))).start();
        (new Thread(new Roommate("john"))).start();
        (new Thread(new Mom())).start();
    }
}

class Bathroom {
    public void use(String who) {
        synchronized (Demo.kitchen) {
            System.out.println(who + " is using bathroom");
            Long time = System.currentTimeMillis();
            while (System.currentTimeMillis() - time < 2000) {
                continue;
            }
            System.out.println(who + " unlocked bathroom");
        }
    }
}

class Kitchen {
    synchronized public void use(String who) {
        System.out.println(who + " is using kitchen");
    }
}

class Roommate implements Runnable {
    private String name;
    public Roommate (String name) { this.name = name; }
    @Override
    public void run() {
        Demo.bathroom.use(name);
    }   
}

class Mom implements Runnable {
    @Override
    public void run() {
        Demo.kitchen.use("mom");
    }   
}

I put 'Demo.kitchen' into parentheses in Bathroom's synchronized block. If anyone is using the bathroom then both the bathroom and the kitchen are locked. Why are they both locked?

I am guessing that:

1) The monitor object itself (the kitchen in my case) becomes locked to all threads (while it is used in synchronized block)

2) Only one thread at a time is allowed to execute the synchronized block if they all have the same monitor object (in my case both roommates had the same bathroom as monitor object)

Is this correct thinking or am i missing something?

Marko Topolnik, thank you for the answer.

I think i understand what is happening now.

First thread1 (bob) starts using the bathroom and locks the kitchen instead (because Demo.kitchen is provided). When john also wants to use bathroom he can't, not because the bathroom is locked, but because he is checking wether the kitchen is locked or not (and bob just locked it). And mom can't use the kitchen, because that is the object which was actually locked.

Was it helpful?

Solution

Be careful not to confuse monitors with the objects they belong to. Generally, it is best to entirely forget about the "object" aspect when thinking about monitors and locks.

Especially, the class where a certain piece of code is declared has nothing to do with the locks being acquired. When you lock Demo.kitchen inside a Bathroom's method, only the kitchen object is locked. Also, locking Demo.kitchen will not prevent other code to concurrently access and change the kitchen object—unless that code is also protected by the same lock.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top