Skip to content

Instantly share code, notes, and snippets.

@yusufcakal
Last active August 16, 2020 13:22
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 yusufcakal/08fd28bd2b17d36a5b440cd69a93f591 to your computer and use it in GitHub Desktop.
Save yusufcakal/08fd28bd2b17d36a5b440cd69a93f591 to your computer and use it in GitHub Desktop.
freeze/unfreeze operations date in java / virtual clock pattern
import java.util.Calendar;
import java.util.Date;
public final class Clock {
private static boolean isFrozen;
private static Date timeSet;
private Clock() {
}
public static synchronized void freeze() {
isFrozen = true;
}
public static synchronized void freeze(Date date) {
freeze();
timeSet = date;
}
public static synchronized void unfreeze() {
isFrozen = false;
timeSet = null;
}
public static Date getTime() {
Calendar calendar = Calendar.getInstance();
if (isFrozen) {
if (timeSet == null) {
timeSet = calendar.getTime();
}
return timeSet;
}
return calendar.getTime();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment