thread safe code : Java Glossary

go to home page T words local find full screen, hide local find menu Google search web for more information on this topic jump to foot of page translate this page with Babelfish by Roedy Green ©1996-2009 Canadian Mind Products
index page for letter ⇒ punctuation 0-9 A B C D E F G H I J K L M N O P Q R S T U V W X Y Z (all)
thread safe code
Thread-safe code is code that will work even if many Threads are executing it simultaneously. Writing it is a black art. It is extremely difficult to debug since you can’t reproduce all possible interactions between Threads. You have to do it by logic. In a computer, something that happens only one in a billion times must be dealt with because on average it will happen once a second. To write code that will run stably for weeks takes extreme paranoia.

Here are your tools for writing thread-safe code.

See the warning under Gotchas:Threads on why a sleeping task may never waken if somebody fiddles with the system clock setting while your thread is asleep.

start versus run

The easiest way to start a Thread is to implement Runnable on some class. All you have to do is say implements Runnable and write a run method that is called when the Thread forks (starts). However you don’t call run directly.

// running on the same thread
aRunnable.run();

If you do, run will be called like a normal method, with no new Thread created. You must create a Thread object and then call start on the Thread object instead.

// starting a Thread
Thread thread = new Thread( aRunnable );
thread.start();
// which will then execute arunnable.run() on a separate Thread.

SwingUtilities.invokeLater

With both SwingUtilities.invokeLater and EventQueue. invokeLater the good news is, even though you are using Runnable, you don’t have the overhead of actually creating a new Thread since you are just calling the run method on the already existing Swing Thread.

You are not on the Swing event thread when main first starts up! You are on it in your event listeners. You are tell if you are on it with:

// Either method will work in
    Java 1.3+
// to determine if you are running on the
dispatch thread,
// the same for AWT or Swing.

// in Swing
boolean onSwingThread 
= javax.
swing.SwingUtilities.
isEventDispatchThread();

// in AWT
boolean onDispatchThread 
= java.
awt.EventQueue.
isDispatchThread();

// Dump info about the current thread, name,
priority, group.
System.
out.println
( Thread.
currentThread() 
);

// Dump name of the current thread
System.
out.println
( Thread.
currentThread().
getName() 
);

One of the most common errors is to tie up the AWT/Swing event thread with some long running computation or even a sleep. Everything freezes up. The GUI can’t respond to mouse clicks and no repainting happens. You have to spin the time-consuming task off on its own thread or use a Timer.

is a Sun class that is not part of the JDK. It lets you convert some long-running event handling code into a separate thread with just a line of extra code.

If you violate these rules, the entire system starts to behave unpredicably and irrationally. If by violating these rules, you manage to create two event-processing threads, life gets really interesting as they unpredictably fight with each other handling Swing events.

Why You Need Synchronized Methods

Let us say you had a method in a banking system like this:
If two threads ran that code simulaneously they might run like this:
thread 1 thread 2
load balance  
  load balance
  add depositAmount2
  store balance
add depositAmount1  
store balance  
You would get an erroneous result balance + depositAmount1 rather than balance + depositAmount1 + depositAmount2.

If instead you wrote:

Then only one thread at a time could access the account record containing the balance field, and the code would have to run like this:
thread 1 thread 2
load balance  
add depositAmount1  
store balance  
  load balance
  add depositAmount2
  store balance
Then you end up with the correct balance when you are done, because the deposit method is run as an atomic (unbreakable/single piece) unit. Further, synchonized means you don’t have to worry about code like this interfering in a deposit() either:
since it too locks the account object containing the balance field.

More Than Just Atomicity

To have multi-thread code work, you need more than just atomic method calls.

For example, imagine a banking system with a getBalance() method to examine the balance, and another withdraw( long withdrawAmount) method to update the a balance.

In a naive system, the teller might first do a transaction that calls the checkBalance() method to look at the balance, and if it has sufficient funds, calls the withdraw method to update the balance.

However, between the method call to look at the balance and update the balance, another withdrawal transaction could come in and snaffle the funds. The withdrawal would improperly go ahead, leaving a correctly-computed overdraft.

thread 1 thread 2
getBalance  
check balance big enough for withdrawal1  
  getBalance
  check balance big enough for withdrawal2
  withdraw( withdrawalAmount2)
withdraw ( withdrawalAmount1)  

For such code to work in a thread-safe way, the withdrawal method must do an atomic integral last-minute check on the balance, as well as an atomic increment on the balance such as the sample code for a withdrawal in the example on why synchronized is needed.

Static

You are more likely to get in thread contention trouble with static members than instance members since there is more sharing of them. Threads tend to play with different objects from other threads, but they share the same static variables.

One trick you can use for static variable contention is to introduce static references to dummy lock objects new Object(). Instead of locking the whole class, you lock just one of the lock objects which represents access to some subset of the member variables. You can also use the techique for instance variables in objects with many threads competing for access.

Books

book cover recommend book⇒Java Concurrency in Practice
 paperbackkindle
ISBN13:978-0-321-34960-6impressioncounterB000RH0EPCclickcounter
ISBN10:0-321-34960-1impressioncounter
publisher:Addison-Wesley
published:2006-05-19
by:Brian Goetz, Tim Peierls, Joshua Bloch, Joseph Bowbeer, David Holmes, Doug Lea
Bloch and Lea especially have very good reputations in concurrent programming. This is the dream team to write such a book. See the companion website with code examples, a sample chapter, errata etc..
UK flag abe books.co.uk abe books.ca Canadian flag
UK flag amazon.co.uk. amazon.ca. Canadian flag
German flag abe books.de chapters.indigo.ca. Canadian flag
German flag amazon.de. abe books.com American flag
French flag abe books.fr amazon.com. American flag
French flag amazon.fr. barnes and noble.com American flag
Italian flag abe books.it powells.com American flag
Spanish flag iberlibro.com abe books anz Australian flag

book cover recommend book⇒Concurrent Programming in Java: Design Principles and Patterns, Second Edition
 paperback
ISBN13:978-0-201-31009-2impressioncounter
ISBN10:0-201-31009-0impressioncounter
publisher:Prentice Hall
published:1999-01-04
by:Doug Lea
432 pages. You can read it online. This is the book on Threads and concurrent programming. The only problem with it is does not cover the new java.util.concurrent package which the author helped design.
UK flag abe books.co.uk abe books.ca Canadian flag
UK flag amazon.co.uk. amazon.ca. Canadian flag
German flag abe books.de chapters.indigo.ca. Canadian flag
German flag amazon.de. abe books.com American flag
French flag abe books.fr amazon.com. American flag
French flag amazon.fr. barnes and noble.com American flag
Italian flag abe books.it powells.com American flag
Spanish flag iberlibro.com abe books anz Australian flag

CMP homejump to top
CMP logo
feedback Please email your feedback for publication, errors, omissions, broken/redirected link reports
and suggestions to improve this page to Roedy Green : feedback email
made with CSS
HTML Checked!
ICRA ratings logo
mindprod.com IP:[65.110.21.43]
Your face IP:[38.103.63.58]
You are visitor number 58,906.
You can get a fresh copy of this page from: or possibly from your local J: drive (Java virtual drive/mindprod.com website mirror)
http://mindprod.com/jgloss/threadsafe.html J:\mindprod\jgloss\threadsafe.html