Skip to content

Commit

Permalink
Fix issue #761: ThreadSafeDoubleCheckLocking.java: Instantiating by R…
Browse files Browse the repository at this point in the history
…eflection call will be successful if you do that firstly (#920)
  • Loading branch information
Azureyjt authored and iluwatar committed Sep 7, 2019
1 parent 8c865e6 commit f141033
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 1 deletion.
4 changes: 4 additions & 0 deletions singleton/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -38,5 +38,9 @@
<artifactId>junit-jupiter-engine</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</dependency>
</dependencies>
</project>
Original file line number Diff line number Diff line change
Expand Up @@ -35,12 +35,16 @@ public final class ThreadSafeDoubleCheckLocking {

private static volatile ThreadSafeDoubleCheckLocking instance;

private static boolean flag = true;

/**
* private constructor to prevent client from instantiating.
*/
private ThreadSafeDoubleCheckLocking() {
// to prevent instantiating by Reflection call
if (instance != null) {
if (flag) {
flag = false;
} else {
throw new IllegalStateException("Already initialized.");
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,11 @@
*/
package com.iluwatar.singleton;

import org.junit.Test;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
* Date: 12/29/15 - 19:26 PM
*
Expand All @@ -36,4 +41,15 @@ public ThreadSafeDoubleCheckLockingTest() {
super(ThreadSafeDoubleCheckLocking::getInstance);
}

/**
* Test creating new instance by refection
*/
@Test(expected = InvocationTargetException.class)
public void testCreatingNewInstanceByRefection() throws Exception {
ThreadSafeDoubleCheckLocking instance1 = ThreadSafeDoubleCheckLocking.getInstance();
Constructor constructor = ThreadSafeDoubleCheckLocking.class.getDeclaredConstructor();
constructor.setAccessible(true);
ThreadSafeDoubleCheckLocking instance2 = (ThreadSafeDoubleCheckLocking) constructor.newInstance(null);
}

}

0 comments on commit f141033

Please sign in to comment.