File tree 3 files changed +25
-1
lines changed
main/java/com/iluwatar/singleton
test/java/com/iluwatar/singleton
3 files changed +25
-1
lines changed Original file line number Diff line number Diff line change 38
38
<artifactId >junit-jupiter-engine</artifactId >
39
39
<scope >test</scope >
40
40
</dependency >
41
+ <dependency >
42
+ <groupId >junit</groupId >
43
+ <artifactId >junit</artifactId >
44
+ </dependency >
41
45
</dependencies >
42
46
</project >
Original file line number Diff line number Diff line change @@ -35,12 +35,16 @@ public final class ThreadSafeDoubleCheckLocking {
35
35
36
36
private static volatile ThreadSafeDoubleCheckLocking instance ;
37
37
38
+ private static boolean flag = true ;
39
+
38
40
/**
39
41
* private constructor to prevent client from instantiating.
40
42
*/
41
43
private ThreadSafeDoubleCheckLocking () {
42
44
// to prevent instantiating by Reflection call
43
- if (instance != null ) {
45
+ if (flag ) {
46
+ flag = false ;
47
+ } else {
44
48
throw new IllegalStateException ("Already initialized." );
45
49
}
46
50
}
Original file line number Diff line number Diff line change 22
22
*/
23
23
package com .iluwatar .singleton ;
24
24
25
+ import org .junit .Test ;
26
+
27
+ import java .lang .reflect .Constructor ;
28
+ import java .lang .reflect .InvocationTargetException ;
29
+
25
30
/**
26
31
* Date: 12/29/15 - 19:26 PM
27
32
*
@@ -36,4 +41,15 @@ public ThreadSafeDoubleCheckLockingTest() {
36
41
super (ThreadSafeDoubleCheckLocking ::getInstance );
37
42
}
38
43
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
+
39
55
}
You can’t perform that action at this time.
0 commit comments