public class BillPughSingleton {
private BillPughSingleton() {
}
private static class SingletonHelper {
private static final BillPughSingleton BILL_PUGH_SINGLETON_INSTANCE = new BillPughSingleton();
}
public static BillPughSingleton getInstance() {
return SingletonHelper.BILL_PUGH_SINGLETON_INSTANCE;
}
}
@Test
void givenSynchronizedLazyLoadedImpl_whenCallgetInstance_thenReturnSingleton() {
// given
Set<BillPughSingleton> setHoldingSingletonObj = new HashSet<>();
List<Future<BillPughSingleton>> futures = new ArrayList<>();
ExecutorService executorService = Executors.newFixedThreadPool(10);
Callable<BillPughSingleton> runnableTask = () -> {
logger.info("run called for:" + Thread.currentThread().getName());
return BillPughSingleton.getInstance();
};
// when
int count = 0;
while(count < 10) {
futures.add(executorService.submit(runnableTask));
count++;
}
futures.forEach(e -> {
try {
setHoldingSingletonObj.add(e.get());
} catch (Exception ex) {
throw new RuntimeException(ex);
}
});
executorService.shutdown();
// then
assertEquals(1, setHoldingSingletonObj.size());
}