Copyright

Java Modifiers: Volatile & Synchronized

Instructor: Benjamin Blanchard

Ben has taught ESL and web programming and has a M.S. in education.

In this lesson, find out why synchronization is important in multithreaded Java applications, and when you'd use one or the other of two important keywords used for synchronization: 'volatile' and 'synchronized.'

Multithreading

One of the more challenging aspects of Java programming is multithreading. Java allows you to create programs that can execute different parts, or even the same part, simultaneously. Why would you want to do this? Well, suppose you want to respond to more than one user at the same time, or your program has to read and write to multiple files while it's providing an uninterrupted user experience. Java allows you to specify parts of your code that can be run concurrently with code in the same program. These are called threads.

So great, you can run parts of a program, even the same part, simultaneously. So, where does synchronization come into it? Well, if you have data that's being manipulated by more than one thread, you may want to make sure that only one thread at a time can change the data. If you don't, you may end up in a situation in which you can't predict what effect the program is going to have. Say you have an office birthday card that needs to be signed by everyone in your group. Everyone can get out their pens at the same time, but you wouldn't want to start writing in the card in the middle of someone else's greeting because you might take up space they were going to need. That's why you need to pass the card around, so that only one person is signing it at any given time. In multithreading, this is called a lock. Often when you have a section of multithreaded code that makes changes in the world, you need to use locking to synchronize those changes. That is, make sure that every thread sees data only when it's in a stable state. The synchronized and volatile keywords are two ways of locking parts of code to achieve this.

So Which One Should You Use?

In the following code, the variable 'occupied' is volatile, and the 'addUser' and 'deleteUser' methods are synchronized.

Example Java code showing volatile and synchronized keywords

As you can see, the most obvious difference between synchronized and volatile is that synchronized is a modifier for methods and blocks of code, while volatile is for fields (otherwise known as 'variables' or 'members'). This distinction, while easy to understand, is not enough to make the determination of which keyword to use. If you need a rule of thumb, I'd say 'When in doubt, use synchronized.' However, volatile can sometimes be more efficient, since it does not block, that is, make other threads wait until it's finished before giving up control. For this reason, you should only use volatile if you know that your program will only access it atomically (i.e. using only one operation), since another thread could access it after only some of the operations have been performed.

An example might be helpful at this point:

Say you have a thread that displays the current number of users signed into a multi-user application. You want to make sure that all threads always see the up-to-date and accurate number of users, so you should synchronize the variable you're using to store the number of users. At first, it might seem like a good candidate for volatile: a single variable set and checked by threads in the program.

However, there's a problem here. Incrementing is actually not an atomic operation, because the state of the variable after the operation relies on the prior state, so it first has to be read, then incremented, then written. If you use a volatile variable, you run the risk of a thread accessing its value in the middle of that three-part operation. So, it's better to put it in a synchronized block.

Example Java code showing synchronized method

To unlock this lesson you must be a Study.com Member.
Create your account

Register to view this lesson

Are you a student or a teacher?

Unlock Your Education

See for yourself why 30 million people use Study.com

Become a Study.com member and start learning now.
Become a Member  Back
What teachers are saying about Study.com
Try it risk-free for 30 days

Earning College Credit

Did you know… We have over 200 college courses that prepare you to earn credit by exam that is accepted by over 1,500 colleges and universities. You can test out of the first two years of college and save thousands off your degree. Anyone can earn credit-by-exam regardless of age or education level.

To learn more, visit our Earning Credit Page

Transferring credit to the school of your choice

Not sure what college you want to attend yet? Study.com has thousands of articles about every imaginable degree, area of study and career path that can help you find the school that's right for you.

Create an account to start this course today
Try it risk-free for 30 days!
Create an account
Support