java.lang.ThreadLocal Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of jtransc-rt Show documentation
Show all versions of jtransc-rt Show documentation
JVM AOT compiler currently generating JavaScript, C++, Haxe, with initial focus on Kotlin and games.
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);
}
}