Home  Synchronization and concurrency  wait/notify  final  volatile  synchronized keyword  Java threading  Deadlock (and avoiding it)  Java 5: ConcurrentHashMap  Atomic variables  Explicit locks  Queues  Semaphores  CountDownLatch  CyclicBarrier

"Piggybacking" on synchronization

This synchronization is rarely advocated as a design pattern (probably with good reason), but I've definitely seen incorrectly synchronized production code that accidentally works by using it! Recall that the Java 5 definition of volatile states that access to a volatile variable synchronizes local copies of all cached variables with main memory. Therefore, it is occasionally possible to write to one variable without synchronization and then take advantage of subsequent synchronization on a different variable to ensure that main memory is updated with both variables.

Cases where this technique will work are essentially where:

  • we know that Thread A will write to the variables;
  • Thread B (and possibly other threads) will read them;
  • there won't be concurrent writes by multiple threads.

Goetz et al (2006: 342-344) briefly discuss use of this technique in some of the Java class library code. The obvious problem with the method for general purpose use is that it may be quite difficult to demonstrate that it is correct in a given circumstance (and in most cases it will almost certainly not be correct...).

Article written by Neil Coffey (@BitterCoffey).


 LetterMeister (word puzzle game for iPhone)
 Currency Quoter (currency converter/predictor)
 French Vocab Games for iPhone/iPad
 Vocabularium: create Spanish vocab podcasts

Java programming articles and tutorials on this site are written by Neil Coffey (@BitterCoffey). Suggestions are always welcome if you wish to suggest topics for Java tutorials or programming articles, or if you simply have a programming question that you would like to see answered on this site. Most topics will be considered. But in particular, the site aims to provide tutorials and information on topics that aren't well covered elsewhere, or on Java performance information that is poorly described or understood. Suggestions may be made via the Javamex blog (see the site's front page for details).
Copyright © Neil Coffey 2015. All rights reserved.