Skip to content

Instantly share code, notes, and snippets.

@hoho4190
Created May 26, 2024 01:48
Show Gist options
  • Save hoho4190/ea9eda9a705596cb951800b51ca4743c to your computer and use it in GitHub Desktop.
Save hoho4190/ea9eda9a705596cb951800b51ca4743c to your computer and use it in GitHub Desktop.
Java: Bill Pugh Singleton
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());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment