"Hi, Amigo!"

"In my previous lessons, I sometimes used the words 'mutex' and 'monitor', now it's time to tell you what they mean."

"I'm all ears."

"A mutex is a special object for synchronizing threads/processes. It has two possible states: busy and free. Simplying things, a mutex is a boolean variable that can have two values: busy (true) and free (false)."

"When a thread wants to take ownership of an object, it marks the object's mutex as busy. And when it is finished working with the object, it marks its mutex as free."

"In other words, a mutex is like a 'busy/free' sign on the door?"

"Yes. And such a mutex is associated with every object in Java. Only the Java machine has direct access to the mutex. It is hidden from the programmer."

"How do we use it then?"

"In Java, we can work with a mutex through a monitor."

"A monitor is a special mechanism (piece of code) layered on top of a mutex. It guarantees proper interaction with the mutex. It's not enough to mark an object as busy. It's still necessary to ensure that other threads don't try to use the busy object."

"In Java, monitors are implemented using the keyword synchronized."

"When you write a synchronized block, the Java compiler replaces it with three pieces of code:"

1) At the beginning of the synchronized block, code is added that marks the mutex as busy.

2) At the end of the synchronized block, code is added that marks the mutex as free.

3) Before the synchronized block, code is added which, if the mutex is busy, causes the thread to wait until the mutex is released.

"Here's roughly how it works:"

Code How it works Description


while (object.mutex)

object.mutex = true;


object.mutex = false;

The thread sleeps as long as the mutex is busy
(we exit the loop when the mutex is released). Mark the mutex as busy.

Execute doTask();

Mark the mutex as free

"In reality, the logic there is different and more complicated. But these are just details."

"Can I have the details?"

"Until you learn how to use it properly, there's no point in getting tangled up in the details."

"A couple of levels back I gave you a list of all thread states with transition arrows and a list of methods that affect this state. Do you remember much?"

"Not really. I just forget everything so quickly…"

"The less practice you do, the less you benefit from the theory."

"By Level 40, you'll learn how to use all of this, and I'll explain how all this actually works. In the meantime, just learn to use it all properly. Got it?"

"Yes, thank you, Ellie."