Published online by Cambridge University Press: 06 July 2010
The basic synchronization primitives provided in Java are very easy to use, and well-suited to the majority of situations a programmer sees. In many respects they are simpler, easier to use, and less prone to errors than their counterparts in POSIX threads (Pthreads). They do not, however, cover all situations and extending them is not always obvious.
PROVIDING PROTECTION
The first thing that synchronization techniques must provide is a method to ensure that updates to shared data are done in a correct fashion. In particular, many updates comprise several distinct operations and those operations must be done together, atomically. The canonical example is a program that updates your bank account. In Listing 1, it should be obvious that thread number 1 could overwrite the data that thread number 2 had just saved.
The solution to this is to ensure that each of those operations happen atomically. In Java, this is done with a synchronized method (objects with such synchronization are known as monitors). Now the second method will have to wait for the one called first to complete before it can start. The code in Listing 2 will operate correctly.
Pthreads accomplishes the same behavior by using explicit mutex locks. While functionally equivalent, using explicit mutexes suffers from the added complexity of the programmer having to remember which locks to use and to unlock them after use. This is not a big problem, but when writing complex code that has numerous branches and return statements, mistakes do happen (I speak from experience!) and it can be irritating to track down.
To save this book to your Kindle, first ensure [email protected] is added to your Approved Personal Document E-mail List under your Personal Document Settings on the Manage Your Content and Devices page of your Amazon account. Then enter the ‘name’ part of your Kindle email address below. Find out more about saving to your Kindle.
Note you can select to save to either the @free.kindle.com or @kindle.com variations. ‘@free.kindle.com’ emails are free but can only be saved to your device when it is connected to wi-fi. ‘@kindle.com’ emails can be delivered even when you are not connected to wi-fi, but note that service fees apply.
Find out more about the Kindle Personal Document Service.
To save content items to your account, please confirm that you agree to abide by our usage policies. If this is the first time you use this feature, you will be asked to authorise Cambridge Core to connect with your account. Find out more about saving content to Dropbox.
To save content items to your account, please confirm that you agree to abide by our usage policies. If this is the first time you use this feature, you will be asked to authorise Cambridge Core to connect with your account. Find out more about saving content to Google Drive.