Last active
July 14, 2023 23:51
-
-
Save bjpeterdelacruz/b1a5b14f3d222fb30468b6edf4f3ce82 to your computer and use it in GitHub Desktop.
What happens when a singleton object is pointing to a new reference?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public final class MyObject { | |
private static int counter = 0; | |
private static Object lock = new Object(); | |
public static void doSomething() { | |
synchronized (lock) { | |
for (int i = 0; i < 100; i++) { | |
counter++; | |
} | |
} | |
} | |
public static void reinitialize() { | |
synchronized (lock) { | |
try { | |
Thread.sleep(5); | |
} catch (InterruptedException e) { | |
throw new RuntimeException(e); | |
} | |
lock = new Object(); | |
} | |
} | |
public static int getCounter() { | |
return counter; | |
} | |
public static void resetCounter() { | |
counter = 0; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment