Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content

Deadlocks - Part II

Let's revisit one of the previous examples and make use of the AtomicInteger class:

import java.util.concurrent.atomic.AtomicInteger;
class DeepThoughtTask implements Runnable {
static AtomicInteger finalResult = new AtomicInteger(0);
private int computeResult() {
return 1; // assume this is a long-running task
public void run() {
// This is lock-free on modern CPUs
public class Main {
public static void main(String args[]) throws Exception {
DeepThoughtTask task = new DeepThoughtTask();
for (int i = 0; i < 42; i++) {
new Thread(task).start();
Thread.sleep(1000); // ad-hoc wait till threads finish
System.out.println("answer: " + DeepThoughtTask.finalResult);
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content