Skip to main content

7 docs tagged with "synchronization"

View All Tags

Condition Variables

Condition variables are another mechanism for synchronizing a program. Condition variables allow threads to enter the waiting state (stop running) until they are signaled/notified by another thread that some condition maybe have been fulfilled and they can take over. The most common example used to illustrate this is a carpark. When the carpark is full you have to wait until a car drives out and it is no longer full. Once this happens you want to be notified that the carpark is no longer full so you can enter the carpark.

Interrupts

Blocking methods can potentially take forever if the condition they are waiting for never occurs which can lead to big issues. For this reason, we want a mechanism to be able to stop/cancel waiting for a given condition and continue with the program.

JMM - Java Memory Model

The Java Memory Model (JMM) specifies guarantees that are given by the Java Virtual Machine (JVM) relating to concurrency:

Safe Object Sharing

There are 2 alternatives to synchronizing objects to make sure that nothing breaks when sharing objects. Either the shared object is immutable which would lead to there never being any inconsistent states between the threads. The other alternative is you just don't have a shared state variable between threads.

Synchronizers

A synchronizer is any object that coordinates and synchronizes the control flow of threads based on its state. The simplest form synchronizer we have already used, being locks.

Threads and Synchronization

Threads are similar to process and allow a program to do multiple things at once by having multiple threads in it. A key difference between threads and process is however that threads share the same global memory and just have their private stack for local variables and function calls and are therefore not as expensive as process which have the big overhead of creating an entire new memory space. This is why threads are also often called lightweight processes.