All Downloads are FREE. Search and download functionalities are using the official Maven repository.

java.lang.ThreadLocal Maven / Gradle / Ivy

Go to download

JVM AOT compiler currently generating JavaScript, C++, Haxe, with initial focus on Kotlin and games.

There is a newer version: 0.6.8
Show newest version
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 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);
	}
}