-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathVirtualClock.java
80 lines (72 loc) · 2.62 KB
/
VirtualClock.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
/*
* Copyright (c) 2015, Parallel Universe Software Co. All rights reserved.
*
* This program and the accompanying materials are license under the terms of the
* MIT license.
*/
package co.paralleluniverse.vtime;
/**
* Sets or gets the virtual clock to be used by the system.
*
* @author pron
*/
public final class VirtualClock {
private static Clock gClock; // lowest priority note that this isn't volatile
private static final InheritableThreadLocal<Clock> itlClock = new InheritableThreadLocal<>(); // medium priority
private static final ThreadLocal<Clock> tlClock = new ThreadLocal<>(); // highest priority
/**
* Puts the given clock in effect for the all threads,
* unless overridden by {@link #setForCurrentThread(Clock) setForCurrentThread}
* or by {@link #setForCurrentThreadAndChildren(Clock) setForCurrentThreadAndChildren}.
*/
public static void setGlobal(Clock clock) {
gClock = clock;
}
/**
* Puts the given clock in effect for the current thread and future child threads,
* unless overridden by {@link #setForCurrentThread(Clock) setForCurrentThread}.
*/
public static void setForCurrentThreadAndChildren(Clock clock) {
itlClock.set(clock);
}
/**
* Puts the given clock in effect for the current thread.
*/
public static void setForCurrentThread(Clock clock) {
tlClock.set(clock);
}
/**
* Puts the given clock in effect for future child threads -- <b>but not the current thread</b> --
* unless overridden by {@link #setForCurrentThread(Clock) setForCurrentThread}.
*/
public static void setForChildThreads(Clock clock) {
final Clock current = get();
setForCurrentThreadAndChildren(clock);
setForCurrentThread(current);
}
/**
* Puts the given clock in effect for the all threads <b>except the current one</b>,
* unless overridden by {@link #setForCurrentThread(Clock) setForCurrentThread}
* or by {@link #setForCurrentThreadAndChildren(Clock) setForCurrentThreadAndChildren}.
*/
public static void setGlobalExceptCurrentThread(Clock clock) {
final Clock current = get();
setGlobal(clock);
setForCurrentThread(current);
}
/**
* Returns the clock currently in effect for the current thread.
*/
public static Clock get() {
Clock clock = tlClock.get();
if (clock == null)
clock = itlClock.get();
if (clock == null)
clock = gClock;
if (clock == null)
clock = SystemClock.instance();
return clock;
}
private VirtualClock() {
}
}