Book Image

Learning Concurrent Programming in Scala

By : Aleksandar Prokopec
5 (1)
Book Image

Learning Concurrent Programming in Scala

5 (1)
By: Aleksandar Prokopec

Overview of this book

Table of Contents (18 chapters)
Learning Concurrent Programming in Scala
Credits
Foreword
About the Author
Acknowledgments
About the Reviewers
www.PacktPub.com
Preface
Index

Monitors and synchronization


In this section, we will study inter-thread communication using the synchronized statement in more detail. As we saw in the previous sections, the synchronized statement serves both to ensure the visibility of writes performed by different threads, and to limit concurrent access to a shared region of memory. Generally speaking, a synchronization mechanism that enforces access limits on a shared resource is called a lock. Locks are also used to ensure that no two threads execute the same code simultaneously; that is, they implement mutual exclusion.

As mentioned previously, each object on the JVM has a special built-in monitor lock, also called the intrinsic lock. When a thread calls the synchronized statement on an x object, it gains ownership of the monitor lock of the x object, given that no other thread owns the monitor. Otherwise, the thread is blocked until the monitor is released. Upon gaining ownership of the monitor, the thread can witness the memory...