From the course: Parallel and Concurrent Programming with Java 1
Unlock the full course today
Join today to access over 22,600 courses taught by industry experts or purchase this course individually.
Atomic variable: Java demo - Java Tutorial
From the course: Parallel and Concurrent Programming with Java 1
Atomic variable: Java demo
- [Instructor] Using a lock to protect a shared variable with mutual exclusion works, but if you're only doing simple operations like incrementing the variables 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 Atomic booleans, 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 a count variable 10 millions times each. I should get an output of 20 million, but since I'm just using a regular integer on line seven, and…
Practice while you learn with exercise files
Download the files the instructor uses to teach the course. Follow along and learn by watching, listening and practicing.