From the course: Complete Guide to Parallel and Concurrent Programming with Java

Unlock this course with a free trial

Join today to access over 25,500 courses taught by industry experts.

Atomic variable: Java demo

Atomic variable: Java demo

- [Lecturer] Using a lock to protect a shared variable with mutual exclusion works, but if you're only doing simple operations like incrementing the variable's value, then a simpler way to do that in Java is by using the atomic package. It provides a collection of classes that support lock-free, thread safe programming on single variables. If I scroll down on the documentation page, I see a variety of classes I can choose from, including AtomicBooleans, Integers, Arrays, Long values, References, and so on. I'll select the Atomic Integer class, and if I scroll down, I can see that it has a variety of methods that implement atomic versions of most standard integer operations. To demonstrate using atomic variables in Java, I'm going to modify the previous example code that I used to demonstrate a data race. It has two parallel threads, incrementing account variable 10 million times each. I should get an output of 20 million, but since I'm just using a regular integer on line seven and I…

Contents