thread safe code : Java Glossary

*0-9ABCDEFGHIJKLMNOPQRSTUVWXYZ (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:

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 (Graphic User Interface) 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 (Java Development Kit). 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 unpredictably 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  If two threads ran that code simultaneously 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, synchronized 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 naïve 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 technique for instance variables in objects with many threads competing for access.

Books

book cover recommend book⇒Java Concurrency in Practiceto book home
by Brian Goetz, Tim Peierls, Joshua J. Bloch, Joseph Bowbeer, David Holmes, Doug Lea 978-0-321-34960-6 paperback
publisher Addison-Wesley 978-0-13-270225-6 eBook
published 2006-05-19 B004V9OA84 kindle
Bloch and Lea especially have very good reputations in concurrent programming. This is the dream team to write such a book.
Australian flag abe books anz abe books.ca Canadian flag
German flag abe books.de amazon.ca Canadian flag
German flag amazon.de Chapters Indigo Canadian flag
Spanish flag amazon.es Chapters Indigo eBooks Canadian flag
Spanish flag iberlibro.com abe books.com American flag
French flag abe books.fr amazon.com American flag
French flag amazon.fr Barnes & Noble American flag
Italian flag abe books.it Nook at Barnes & Noble American flag
Italian flag amazon.it Kobo American flag
India flag junglee.com Google play American flag
UK flag abe books.co.uk O’Reilly Safari American flag
UK flag amazon.co.uk Powells American flag
UN flag other stores
Greyed out stores probably do not have the item in stock. Try looking for it with a bookfinder.
book cover recommend book⇒Concurrent Programming in Java(TM): Design Principles and Patterns, third editionto book home
by Douglas Lea 978-0-321-25617-1 paperback
publisher Addison-Wesley
published 2006-05-19
Threads and concurrency in Java, design considerations (safety, liveness and performance), Before/After Patterns, layering, adapters, immutability and synchronization, deadlock, resource ordering, the Java Memory Model and concurrency, using the java.concurrency package, confinement, refactoring for concurrency, mutexes, read-write locks, recovering from failure, notifications, semaphores, latches, exchanges, transactions, one-way messages, worker threads, polling and event-driven I/O, parallelism techniques (fork/join, computation trees and barriers), Communicating Sequential Processes (CSP).
Australian flag abe books anz abe books.ca Canadian flag
German flag abe books.de amazon.ca Canadian flag
German flag amazon.de Chapters Indigo Canadian flag
Spanish flag amazon.es Chapters Indigo eBooks Canadian flag
Spanish flag iberlibro.com abe books.com American flag
French flag abe books.fr amazon.com American flag
French flag amazon.fr Barnes & Noble American flag
Italian flag abe books.it Nook at Barnes & Noble American flag
Italian flag amazon.it Kobo American flag
India flag junglee.com Google play American flag
UK flag abe books.co.uk O’Reilly Safari American flag
UK flag amazon.co.uk Powells American flag
UN flag other stores
Greyed out stores probably do not have the item in stock. Try looking for it with a bookfinder.

Learning More

Oracle’s Javadoc on java.util.concurrent package : available:
Oracle’s Javadoc on Thread class : available:
Oracle’s Javadoc on Queue interface : available:
Oracle’s Javadoc on setDefaultUncaughtExceptionHandler class : available:
Oracle’s Javadoc on AtomicLong class : available:
Oracle’s Javadoc on AtomicReference class : available:

This page is posted
on the web at:

http://mindprod.com/jgloss/threadsafe.html

Optional Replicator mirror
of mindprod.com
on local hard disk J:

J:\mindprod\jgloss\threadsafe.html
Canadian Mind Products
Please the feedback from other visitors, or your own feedback about the site.
Contact Roedy. Please feel free to link to this page without explicit permission.

IP:[65.110.21.43]
Your face IP:[3.137.163.165]
You are visitor number