Skip to content

Instantly share code, notes, and snippets.

@freyacodes
Created January 16, 2018 16:34
Show Gist options
  • Save freyacodes/db54d1b53d3a214f9ddb9f8ef3afb7ae to your computer and use it in GitHub Desktop.
Save freyacodes/db54d1b53d3a214f9ddb9f8ef3afb7ae to your computer and use it in GitHub Desktop.
Normal int, volatile int, and AtomicInteger thread safety comparison
import java.util.concurrent.atomic.AtomicInteger;
public class scratch extends Thread {
public static int x = 0;
public static volatile int y = 0;
public static AtomicInteger z = new AtomicInteger(0);
public static void main(String[] args) {
for (int i = 0; i < 1000; i++) {
new scratch().start();
}
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.printf("x: %d\ny: %d\nz: %d", x, y, z.get());
}
@Override
public void run() {
for (int i = 0; i < 10000; i++) {
x++;
y++;
z.incrementAndGet();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment