mirror of
https://github.com/tiennm99/java-design-patterns.git
synced 2026-05-14 12:58:37 +00:00
docs: update singleton
This commit is contained in:
@@ -89,7 +89,7 @@ public class App {
|
||||
LOGGER.info("enumIvoryTower1={}", enumIvoryTower1);
|
||||
LOGGER.info("enumIvoryTower2={}", enumIvoryTower2);
|
||||
|
||||
// double checked locking
|
||||
// double-checked locking
|
||||
var dcl1 = ThreadSafeDoubleCheckLocking.getInstance();
|
||||
LOGGER.info(dcl1.toString());
|
||||
var dcl2 = ThreadSafeDoubleCheckLocking.getInstance();
|
||||
|
||||
@@ -45,7 +45,7 @@ public final class BillPughImplementation {
|
||||
}
|
||||
|
||||
/**
|
||||
* The InstanceHolder is a static inner class and it holds the Singleton instance.
|
||||
* The InstanceHolder is a static inner class, and it holds the Singleton instance.
|
||||
* It is not loaded into memory until the getInstance() method is called.
|
||||
*/
|
||||
private static class InstanceHolder {
|
||||
|
||||
@@ -62,7 +62,7 @@ public final class ThreadSafeDoubleCheckLocking {
|
||||
// Check if singleton instance is initialized.
|
||||
// If it is initialized then we can return the instance.
|
||||
if (result == null) {
|
||||
// It is not initialized but we cannot be sure because some other thread might have
|
||||
// It is not initialized, but we cannot be sure because some other thread might have
|
||||
// initialized it in the meanwhile.
|
||||
// So to make sure we need to lock on an object to get mutual exclusion.
|
||||
synchronized (ThreadSafeDoubleCheckLocking.class) {
|
||||
@@ -72,7 +72,7 @@ public final class ThreadSafeDoubleCheckLocking {
|
||||
// just like the previous null check.
|
||||
result = instance;
|
||||
if (result == null) {
|
||||
// The instance is still not initialized so we can safely
|
||||
// The instance is still not initialized, so we can safely
|
||||
// (no other thread can enter this zone)
|
||||
// create an instance and make it our singleton instance.
|
||||
result = new ThreadSafeDoubleCheckLocking();
|
||||
|
||||
@@ -85,7 +85,7 @@ abstract class SingletonTest<S> {
|
||||
* Test singleton instance in a concurrent setting.
|
||||
*/
|
||||
@Test
|
||||
void testMultipleCallsReturnTheSameObjectInDifferentThreads() throws Exception {
|
||||
void testMultipleCallsReturnTheSameObjectInDifferentThreads() {
|
||||
assertTimeout(ofMillis(10000), () -> {
|
||||
// Create 10000 tasks and inside each callable instantiate the singleton class
|
||||
final var tasks = IntStream.range(0, 10000)
|
||||
@@ -96,7 +96,7 @@ abstract class SingletonTest<S> {
|
||||
final var executorService = Executors.newFixedThreadPool(8);
|
||||
final var results = executorService.invokeAll(tasks);
|
||||
|
||||
// wait for all of the threads to complete
|
||||
// wait for all the threads to complete
|
||||
final var expectedInstance = this.singletonInstanceMethod.get();
|
||||
for (var res : results) {
|
||||
final var instance = res.get();
|
||||
|
||||
Reference in New Issue
Block a user