@Test public void testRaceConditionInLazyInit() { LazyInitRace lazy = new LazyInitRace(); Thread th_1 = new Thread(() -> { exObject_1 = lazy.getInstance(); }); Thread th_2 = new Thread(() -> { exObject_2 = lazy.getInstance(); }); th_1.start(); th_2.start(); try { th_1.join(); th_2.join(); } catch (InterruptedException e) { e.printStackTrace(); } assertEquals(exObject_1, exObject_2); }
public ExpensiveObject getInstance() { if (instance == null) { threadDelay(); instance = new ExpensiveObject(); } return instance; }
LazyInitRace { public ExpensiveObject getInstance() { if (instance == null) { threadDelay(); instance = new ExpensiveObject(); } return instance; } }
LazyInitRace { public ExpensiveObject getInstance() { if (instance == null) { threadDelay(); instance = new ExpensiveObject(); } return instance; }  }
LazyInitRace { public ExpensiveObject getInstance() { if (instance == null) { threadDelay(); instance = new ExpensiveObject(); } return instance; }  ExpensiveObject getInstance(); }
LazyInitRace { public ExpensiveObject getInstance() { if (instance == null) { threadDelay(); instance = new ExpensiveObject(); } return instance; }  ExpensiveObject getInstance();  }