85. The synchronized modifier
The synchronized keyword is used in concurrent environments in which multiple threads are operating and there’s potential that code running on different threads are interacting on the same section of code. The synchronized modifier is used to indicate that the associated element can only be accessed by one caller at a time. In the code below you’ll see the various applications of synchronized available:
synchronizedclass PrizePool {
synchronized amount
static synchronized pools
synchronized calculateTotalPool() {
//synchronized code
}
def calculateWinnings() {
//non-synchronized code
synchronized (this) {
//synchronized code
}
//non-synchronized code
}
static synchronized removePool() {
//synchronized code
}
static addPool() {
//non-synchronized code
synchronized (PrizePool) {
//synchronized code
}
//non-synchronized code
}
}
- First of all, member and static variables can be marked as
synchronized- only one thread can read/write the variable at a time. - Instance and class methods can also be marked as
synchronized. Once called by one thread, any other threads are prevented from accessing the method until the first thread’s call has completed. - One or more blocks within an instance or class method can be
synchronized1:- Within an instance method the block is prefixed with
synchronized (this)- note the use of an object instance (this) - For a class method, the block is prefixed with
synchronized (PrizePool)- note the use of a class name (PrizePool)
- Within an instance method the block is prefixed with
A good starting place for understanding this topic is the Concurrency section of The Java Tutorials. Additionally, the GPars Framework provides a library to assist you in writing concurrent/parallel Groovy and Java code.
- Whilst the example blocks use
thisinstance and thePrizePoolclass, you can use other instances and classes.↩