When writing multithreaded applications,
sometimes you need to control access to certain pieces of data in a
class. While you may know that you can use the synchronized keyword
to achieve this goal, you may not know that you can also use the
volatile keyword to get a similar effect—without all of the
overhead of the synchronized keyword.

If multiple threads have access to the same
variable, the JVM may (and probably will) let each thread keep its
own copy of the variable. Changes to the variable by one thread may
or may not be seen by other threads; using the volatile keyword
essentially synchronizes access to a variable. When you declare a
variable with the volatile keyword, the JVM must make sure that all
threads accessing the variable have their copies updated whenever
the variable is modified.

When a thread invokes a synchronized method or
code block, the thread must acquire the object’s lock. When the
thread leaves the synchronized code, the lock must be released.
Acquiring and releasing an object’s lock requires time and
resources. By using the volatile keyword, you can avoid this
overhead; however, using volatile isn’t free. Keeping a volatile
field’s value synced between all threads also carries a cost. I
think the Java Language Specification says it best: “A field may be
declared volatile, in which case, a thread must reconcile its
working copy of the field with the master copy every time it
accesses the variable.”

Determining whether to use the volatile keyword
or the synchronized method should be evaluated on an
application-by-application basis. The next time you need to
synchronize data access, examine both options to see which one will
work for you.

Delivered each Thursday, our free Java newsletter provides insight and hands-on tips you need to unlock the full potential of this programming language. Automatically sign up today!