Newsletter sign-up
View all newsletters

Sign up for our Enterprise Java Newsletter

Enterprise Java

Design for thread safety

Design tips on when and how to use synchronization, immutable objects, and thread-safe wrappers

  • Digg
  • Reddit
  • SlashDot
  • Stumble
  • del.icio.us
  • Technorati
  • dzone
Six months ago I began a series of articles about designing classes and objects. In this month's Design Techniques column, I'll continue that series by looking at design principles that concern thread safety. This article tells you what thread safety is, why you need it, when you need it, and how to go about getting it.

What is thread safety?

Thread safety simply means that the fields of an object or class always maintain a valid state, as observed by other objects and classes, even when used concurrently by multiple threads.

One of the first guidelines I proposed in this column (see "Designing object initialization") is that you should design classes such that objects maintain a valid state, from the beginning of their lifetimes to the end. If you follow this advice and create objects whose instance variables all are private and whose methods only make proper state transitions on those instance variables, you're in good shape in a single-threaded environment. But you may get into trouble when more threads come along.

Multiple threads can spell trouble for your object because often, while a method is in the process of executing, the state of your object can be temporarily invalid. When just one thread is invoking the object's methods, only one method at a time will ever be executing, and each method will be allowed to finish before another method is invoked. Thus, in a single-threaded environment, each method will be given a chance to make sure that any temporarily invalid state is changed into a valid state before the method returns.

Once you introduce multiple threads, however, the JVM may interrupt the thread executing one method while the object's instance variables are still in a temporarily invalid state. The JVM could then give a different thread a chance to execute, and that thread could call a method on the same object. All your hard work to make your instance variables private and your methods perform only valid state transformations will not be enough to prevent this second thread from observing the object in an invalid state.

Such an object would not be thread-safe, because in a multithreaded environment, the object could become corrupted or be observed to have an invalid state. A thread-safe object is one that always maintains a valid state, as observed by other classes and objects, even in a multithreaded environment.

Why worry about thread safety?

There are two big reasons you need to think about thread safety when you design classes and objects in Java:

  1. Support for multiple threads is built into the Java language and API

  2. All threads inside a Java virtual machine (JVM) share the same heap and method area


Because multithreading is built into Java, it is possible that any class you design eventually may be used concurrently by multiple threads. You needn't (and shouldn't) make every class you design thread-safe, because thread safety doesn't come for free. But you should at least think about thread safety every time you design a Java class. You'll find a discussion of the costs of thread safety and guidelines concerning when to make classes thread-safe later in this article.

  • Digg
  • Reddit
  • SlashDot
  • Stumble
  • del.icio.us
  • Technorati
  • dzone
Comments (7)
Login
Forgot your account info?

totally wonderfullBy Anonymous on January 29, 2010, 11:01 amtotally wonderfull

Reply | Read entire comment

Great StuffBy Anonymous on November 16, 2009, 8:40 amGreat article .Easy to understand .Good Job

Reply | Read entire comment

This is really a great stuff...By Nathanial on October 26, 2009, 12:59 pmThis is really a great stuff for sharing.keep it up .Thanks for sharing. free advertising |part time jobs |steam shower

Reply | Read entire comment

Where exactly is this new pattern documented? Could you please pBy sarikan on September 11, 2009, 6:40 amWhere exactly is this new pattern documented? Could you please provide a link for it? Thanks!

Reply | Read entire comment

RE: read/write thread safetyBy Mohan on September 7, 2009, 7:57 amI was not aware of the new thread pattern, thanks for updating us it really works like magic. Kudos to Sun they have come a long way with java and made it really...

Reply | Read entire comment

View all comments

Add comment
Anonymous comments subject to approval. Register here for member benefits.
Have a JavaWorld account? Log in here. Register now for a free account.
Resources
  • The discussion forum devoted to the material presented in this article. http://www.artima.com/flexiblejava/fjf/threadsafety/index.html
  • Recommended books on Java design http://www.artima.com/designtechniques/booklist.html
  • Source packet that contains the example code used in this article http://www.artima.com/flexiblejava/code.html
  • Source code for the JVM Simulator applets, which, as mentioned in the article, include some thread-safe classes. Look at JVMSimulator and Method.java and search for sychronized. http://www.artima.com/insidejvm/applets/sourcecode.html
  • Object orientation FAQ http://www.cyberdyne-object-sys.com/oofaq/
  • 7237 Links on Object Orientation http://www.rhein-neckar.de/~cetus/software.html
  • The Object-Oriented Page http://www.well.com/user/ritchie/oo.html
  • Collection of information on OO approach http://arkhp1.kek.jp:80/managers/computing/activities/OO_CollectInfor/OO_CollectInfo.html
  • Design Patterns Home Page http://hillside.net/patterns/patterns.html
  • A Comparison of OOA and OOD Methods http://www.iconcomp.com/papers/comp/comp_1.html
  • Object-Oriented Analysis and Design MethodsA Comparative Review http://wwwis.cs.utwente.nl:8080/dmrg/OODOC/oodoc/oo.html
  • Patterns discussion FAQ http://gee.cs.oswego.edu/dl/pd-FAQ/pd-FAQ.html
  • Implementing Basic Design Patterns in Java (Doug Lea) http://www.oswego.edu/dl/pats/ifc.html
  • Patterns in Java AWT http://mordor.cs.hut.fi/tik-76.278/group6/awtpat.html
  • Software Technology's Design Patterns Page http://www.sw-technologies.com/dpattern/
  • Previous Design Techniques articles http://www.javaworld.com/topicalindex/jw-ti-techniques.html