Skip to content

Commit f141033

Browse files
Azureyjtiluwatar
authored andcommitted
Fix issue iluwatar#761: ThreadSafeDoubleCheckLocking.java: Instantiating by Reflection call will be successful if you do that firstly (iluwatar#920)
1 parent 8c865e6 commit f141033

File tree

3 files changed

+25
-1
lines changed

3 files changed

+25
-1
lines changed

singleton/pom.xml

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,5 +38,9 @@
3838
<artifactId>junit-jupiter-engine</artifactId>
3939
<scope>test</scope>
4040
</dependency>
41+
<dependency>
42+
<groupId>junit</groupId>
43+
<artifactId>junit</artifactId>
44+
</dependency>
4145
</dependencies>
4246
</project>

singleton/src/main/java/com/iluwatar/singleton/ThreadSafeDoubleCheckLocking.java

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,12 +35,16 @@ public final class ThreadSafeDoubleCheckLocking {
3535

3636
private static volatile ThreadSafeDoubleCheckLocking instance;
3737

38+
private static boolean flag = true;
39+
3840
/**
3941
* private constructor to prevent client from instantiating.
4042
*/
4143
private ThreadSafeDoubleCheckLocking() {
4244
// to prevent instantiating by Reflection call
43-
if (instance != null) {
45+
if (flag) {
46+
flag = false;
47+
} else {
4448
throw new IllegalStateException("Already initialized.");
4549
}
4650
}

singleton/src/test/java/com/iluwatar/singleton/ThreadSafeDoubleCheckLockingTest.java

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,11 @@
2222
*/
2323
package com.iluwatar.singleton;
2424

25+
import org.junit.Test;
26+
27+
import java.lang.reflect.Constructor;
28+
import java.lang.reflect.InvocationTargetException;
29+
2530
/**
2631
* Date: 12/29/15 - 19:26 PM
2732
*
@@ -36,4 +41,15 @@ public ThreadSafeDoubleCheckLockingTest() {
3641
super(ThreadSafeDoubleCheckLocking::getInstance);
3742
}
3843

44+
/**
45+
* Test creating new instance by refection
46+
*/
47+
@Test(expected = InvocationTargetException.class)
48+
public void testCreatingNewInstanceByRefection() throws Exception {
49+
ThreadSafeDoubleCheckLocking instance1 = ThreadSafeDoubleCheckLocking.getInstance();
50+
Constructor constructor = ThreadSafeDoubleCheckLocking.class.getDeclaredConstructor();
51+
constructor.setAccessible(true);
52+
ThreadSafeDoubleCheckLocking instance2 = (ThreadSafeDoubleCheckLocking) constructor.newInstance(null);
53+
}
54+
3955
}

0 commit comments

Comments
 (0)