---------------
Christof Meerwald@java_sync.notes

home
> notes
>> java sync

translate to German (by SYSTRAN)

Java Synchronisation

Even tough monitors could rather trivially be mapped to mutexes and condition variables in Java, most of the work is handled internally and only a simple park/unpark interface (see PlatformEvent::park and PlatformEvent::unpark) is used to put threads into a sleeping state.

Note: PlatformEvent::park maps onto pthread_cond_wait on Linux (and Solaris if you don't set UseLWPSynchronization - otherwise it maps to lwp_cond_wait)

As might be expected, uncontended synchronisation is handled entirely in user-space.

Contended Synchronisation

When a monitor is contended, a simple synchronized block will be mapped to roughly (simplified) the following native code:

> java_sync_contended.c:

pthread_mutex_lock(&mutex);
while (locked) {
    pthread_cond_wait(&cond, &mutex);
}
locked = 1;
pthread_mutex_unlock(&mutex);

// do something

pthread_mutex_lock(&mutex);
locked = 0;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);

notify/notifyAll

To avoid contention when waking up threads via notify or notifyAll, Java queues the thread(s) for wakeup when releasing the monitor (one at a time).

Resources

---------------

This Web page is licensed under the Creative Commons Attribution - NonCommercial - Share Alike License. Any use is subject to the Privacy Policy.

Revision: 1.2, cmeerw.org/notes/java_sync.html
Last modified: Mon Sep 03 18:20:51 2018
Christof Meerwald <cmeerw@cmeerw.org>
XMPP: cmeerw@cmeerw.org