Thread Synchronization

 

 

 

Foreword

Resources

Code Listings

Foil Sets

Assignments

Solutions

External Resources

SiteMap

Search

Home

 

 

Up ] Introductory Examples ] Object Cloning ] Static Method's ] Sleep and Locks ] Thread Primer ] Daemon Threads ] [ Thread Synchronization ] Gaurded Suspension ] Deadlock ] Virtual Machine Threads ] Volitility ] Wait-Notify ]

In Java, two threads can communicate by accessing a shared variable (shared-memory model). If two threads can both modify an object, that is, they can both execute a method that assigns to a shared variable, then the modifications must be synchronized. This is easy - just declare the method to be synchronized! This means that Java will ensure that only one thread executes the method at a time.

When we employ synchronized methods, the scope of the lock is the execution time of these methods. This execution time, is sometimes referred to as the method scope. It should be noted, however, that the lock is based on a specific object and not on any particular method. Besides synchronization is based on actual objects, not references to objects

We now look at the inner workings of synchronized methods vis-à-vis unsynchronized methods. In this context we have a message queue object to which two threads add and remove messages. We start off with having both the methods add() and remove() in the message queue as synchronized methods and then proceed to experiment with these methods.

Source

EmptyQueueThread.java

FillQueueThread.java

MsgQueue.java

SimpleScheduler.java

Test.java

JAR Files: Please refer to the Java-Basics section for more information on using JAR files.

Test.jar