Back
Close

Computing with Data

elgeish
31.1K views
Previous: Ineffectual Synchronization - Part III Next: Starvation

Synchronization vs. Volatility

class DeepThoughtTask implements Runnable {
static int finalResult = 0;
private int computeResult() {
return 1; // assume this is a long-running task
}
public void run() {
long partialResult = computeResult(); // lock-free
synchronized (DeepThoughtTask.class) {
finalResult += partialResult;
}
}
}
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);
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Create your playground on Tech.io
This playground was created on Tech.io, our hands-on, knowledge-sharing platform for developers.
Go to tech.io
codingame x discord
Join the CodinGame community on Discord to chat about puzzle contributions, challenges, streams, blog articles - all that good stuff!
JOIN US ON DISCORD
Online Participants