Skip to content

Instantly share code, notes, and snippets.

@bjpeterdelacruz
Last active July 14, 2023 23:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bjpeterdelacruz/b1a5b14f3d222fb30468b6edf4f3ce82 to your computer and use it in GitHub Desktop.
Save bjpeterdelacruz/b1a5b14f3d222fb30468b6edf4f3ce82 to your computer and use it in GitHub Desktop.
What happens when a singleton object is pointing to a new reference?
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