Java Glossary : thread safe code

CMP home Java glossary home Menu no menu Last updated 2004-06-30 by Roedy Green ©1996-2004 Canadian Mind Products

Java definitions: 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

You are here : home : Java Glossary : T words : thread safe code.

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.

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.

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

Swing Threads

Unlike the AWT, Swing is not threadsafe. You can't directly meddle with Swing components, or their backing data models from a second thread. The contract is, if you want to do anything to a Swing component that could have any effect on it's display from an application thread (not the EventDispatchThread itself), you should add it to the event dispatch thread's queue via SwingUtilities.invokeLater( Runnable ) or SwingUtilities.invokeAndWait( Runnable ) so that it will be done on the same thread that Swing itself uses. 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.

There are a few exceptions to this general rule, most notably it is safe to call repaint and revalidate, JTextComponent.setText and JTextArea.append from any thread.


CMP logo
CMP_home
home
Canadian Mind Products CSS
HTML Checked!
ICRA ratings logo
mindprod.com IP:[24.87.56.253]
Your IP:[80.134.30.163]
You are visitor number 4518.
Please send errors, omissions and suggestions
to improve this page to Roedy Green.
You can get a fresh copy of this page from: or possibly from your local J: drive mirror:
http://mindprod.com/jgloss/threadsafe.html J:\mindprod\jgloss\threadsafe.html