O'Reilly logo

Java Cookbook by Ian F. Darwin

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Thread Communication: Synchronized Code

Problem

You need to protect certain data from access by multiple threads.

Solution

Use the synchronized keyword on the method or code you wish to protect.

Discussion

I discussed the synchronized keyword briefly in Section 16.5. This keyword specifies that only one thread at a time is allowed to run the given code. You can synchronize methods or smaller blocks of code. It is easier and safer to synchronize entire methods, but this can be more costly in terms of blocking threads that could run. Simply add the synchronized keyword on the method. For example, many of the methods of Vector (see Section 7.4) are synchronized.[57] This ensures that the vector does not become corrupted or give incorrect results when two threads update or retrieve from it at the same time.

Bear in mind that threads can be interrupted at almost any time and control given to another thread. Consider the case of two threads appending to a data structure at the same time. Let’s suppose we have the same methods as Vector, but we’re operating on a simple array. The add( ) method simply uses the current number of objects as an array index, then increments it:

1 public void add(Object obj) {
2    data[max] = obj;
3    max = max + 1;
4 }

Threads A and B both wish to call this method. Now suppose that Thread A gets interrupted after line 2 but before line 3, and then Thread B gets to run. Thread B does line 2, overwriting the contents of data[max]; we’ve now lost all reference to the ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required