Atomic Variables in Java: Definition & Example

Instructor: Martin Gibbs

Martin has 16 years experience in Human Resources Information Systems and has a PhD in Information Technology Management. He is an adjunct professor of computer science and computer programming.

What if you could have a runway that allows simultaneous take-offs and landings? Although it might sound like we should be doing physics, Java has atomic variables that allow for multi-use runways. This lesson will define the concept and provide an example of an atomic variable in action.

Synchronization

The whole reason for atomic variables is for synchronization purposes during multi-threaded operations. Multi-threading is a lot like multi-tasking, parts of a Java program can be running at the same time, performing different updates or calculations. But, what happens when two or more threads try to access the same variable? In that case, you can wind up with a lock on the data. That is, no updates can be made until the lock is released. Thread A might lock the counter variable while it's running, then release to Thread B.

If you don't want to wait, you need what's called a non-blocking algorithm. This means that nobody has to wait. It's like everybody has a green light in a traffic intersection, but no cars hit one another.

Atomic

Java provides a utility for keeping things in sync. The atomic variables ensure synchronization. With multi-threading, we need to have the ability to ensure that our threads don't crash into each other or cause issues with data changes.

Atomic Variables

The atomic package includes the following variables that are available to use:

  • AtomicInteger
  • AtomicLong
  • AtomicBoolean
  • AtomicIntegerArray
  • AtomicLongArray

For most purposes, integers and booleans are the types of variables that would be updated by multiple threads. These include counters or flags/switches that flip on/off during processing.

Atomic Variables in Action

Now that we've covered the theory, let's look at some working code. Before we can start using atomic variables, however, we have to import a Java utility that gives us the tools to use this feature.

Import Utility

First we need to import a Java utility that provides the information needed to use atomic variables. There are large number of utilities that Java provides but doesn't automatically add to your code. This helps reduce overhead and processing time. In order to use these utilities, you import them with an import statement at the very top of your code.


Java concurrent utility


The previous code imports the entire set of classes for atomic variables. If you want to save a little processing time, you can import only the set of atomic variables you will be using. The most common is the integer. Therefore, you can reduce the complexity a little bit by importing only the AtomicInteger class:


Java util AtomicInteger


Both import statements are valid, but the second is cleaner and only brings in the tools you'll need if you only use the atomic integer. In our case, we'll be focusing only on the integer. Our code will use a counter in a multi-threaded example.

Using an Atomic Variable

Now it gets interesting. The example we will build has a lot of detail, so we will step through it, and then provide the full program code.

The first thing we need to do is create our main class, and a new atomic variable. Declaring the atomic variable is like creating a new class. We are creating a new instance of an AtomicInteger, the class provided in the utility we imported.


Java new atomic integer


The next part of the code is what lets us do multi-threading. There is a delivered interface in Java called Runnable. If we declare a class that uses Runnable, we can create threads to run simultaneously.


Java atomic runnable interface


Next, we'll declare a local integer value. We'll use this as part of the processing during the multi-threading operation.


Java atomic local integer


The next part of the code uses one of the features of the utility we just imported. The incrementAndGet function increments (adds 1 to) the variable. This sounds simple, but if we are multi-threading, we have to be careful that twelve other functions don't try to increment our counter, and give us a completely bogus result!

The next part of the print statement (System.out.println) returns the ID of the thread we are running.


Java atomic increment


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