File tree Expand file tree Collapse file tree
main/java/com/iluwatar/singleton
test/java/com/iluwatar/singleton Expand file tree Collapse file tree Original file line number Diff line number Diff line change 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 >
Original file line number Diff line number Diff 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 }
Original file line number Diff line number Diff line change 2222 */
2323package 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}
You can’t perform that action at this time.
0 commit comments