![JAR search and dependency download from the Maven repository](/logo.png)
java.lang.ThreadLocal Maven / Gradle / Ivy
package java.lang;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.function.Supplier;
// @TODO: This is slow, this should be implemented different in each target.
public class ThreadLocal {
private Map valuesPerThread = new HashMap();
private Set initialized = new HashSet();
protected T initialValue() {
return null;
}
public ThreadLocal() {
}
public static ThreadLocal withInitial(Supplier extends S> supplier) {
return new ThreadLocal() {
@Override
protected S initialValue() {
return supplier.get();
}
};
}
private long initializeOnce() {
long id = Thread.currentThread().getId();
if (!initialized.contains(id)) {
initialized.add(id);
valuesPerThread.put(id, initialValue());
}
return id;
}
public T get() {
long id = initializeOnce();
return valuesPerThread.get(id);
}
public void set(T value) {
long id = initializeOnce();
valuesPerThread.put(id, value);
}
public void remove() {
long id = initializeOnce();
valuesPerThread.put(id, null);
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy