The problem will be with the isCorrect method and to be perfectly accurate with the synchronization of the private synchronized method of the computeCorrectess ()
All streams that have reached this method will be in a queue after passing a logical fork:
if (!correct) { }
and as it is further understood, the first incoming stream will change the state of the flag, but a queue of threads may already be formed. Verification code:
public class SomeClass implements Runnable { SomeData someData = new SomeData(); public static void main(String[] args) { new SomeClass().threadsGenerator(); } private void threadsGenerator() { for (int i = 0; i < 10; i++) { new Thread(this).start(); } } @Override public void run() { try { someData.isCorrect(); } catch (InterruptedException e) { e.printStackTrace(); } } public class SomeData { private boolean correct; private boolean computed; public SomeData() { correct = false; computed = false; } public boolean isCorrect() throws InterruptedException { if (!correct) { computeCorrectess(); } return correct; } private synchronized void computeCorrectess() throws InterruptedException { System.out.println(correct); TimeUnit.SECONDS.sleep(1); correct = true; } } }
recommend reading