MCPcopy Create free account
hub / github.com/traneio/future / Local

Class Local

future-java/src/main/java/io/trane/future/Local.java:82–191  ·  view source on GitHub ↗

`Local`s are a mechanism similar to `ThreadLocal` but for asynchronous computations. It is not possible to use `ThreadLocal`s with `Future` because the data it holds become invalid when the computation reaches an asynchronous boundary. The thread returns to its thread pool to execute other computat

Source from the content-addressed store, hash-verified

80 * the type of the local value.
81 */
82public final class Local<T> {
83
84 protected static final Optional<?>[] EMPTY = new Optional<?>[0];
85 private static ThreadLocal<Optional<?>[]> threadLocal = null;
86 private static int size = 0;
87
88 /**
89 * Creates a new local value.
90 *
91 * @param <T> the type of the local value.
92 * @return the local value
93 */
94 public static final <T> Local<T> apply() {
95 return new Local<>();
96 }
97
98 protected static final Optional<?>[] save() {
99 if (threadLocal == null)
100 return EMPTY;
101 else {
102 Optional<?>[] state = threadLocal.get();
103 if (state == null)
104 return EMPTY;
105 else
106 return state;
107 }
108 }
109
110 protected static final void restore(final Optional<?>[] saved) {
111 if (threadLocal != null)
112 threadLocal.set(saved);
113 }
114
115 private static final synchronized int newPosition() {
116 if (threadLocal == null)
117 threadLocal = new ThreadLocal<>();
118 return size++;
119 }
120
121 private final int position = newPosition();
122
123 private Local() {
124 }
125
126 /**
127 * Updates the local with the provided value.
128 *
129 * @param value value to set
130 */
131 public final void update(final T value) {
132 set(Optional.of(value));
133 }
134
135 /**
136 * Sets the value of the local. It's similar to update but receives an
137 * optional value.
138 *
139 * @param opt optional value to set.

Callers

nothing calls this directly

Calls 1

newPositionMethod · 0.95

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…