If you need to control access to certain pieces of data in a class when writing multithreaded applications, see how you can use the volatile keyword to get a similar effect as using the synchronised keyword.
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 synchronised 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 synchronised 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 synchronises 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 synchronised method or code block, the thread must acquire the object's lock. When the thread leaves the synchronised 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 synchronised method should be evaluated on an application-by-application basis. The next time you need to synchronise data access, examine both options to see which one will work for you.




Leave a comment