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

fish.payara.nucleus.requesttracing.store.IterableThreadLocal Maven / Gradle / Ivy

There is a newer version: 7.2024.1.Alpha1
Show newest version
package fish.payara.nucleus.requesttracing.store;

import static java.util.Collections.synchronizedMap;

import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.WeakHashMap;
import java.util.function.Supplier;

/**
 * A {@link ThreadLocal} that allows to iterate over all available {@link Thread}-value pairs.
 * Note that this is not strongly consistent and may differ from actual current state in moment of change.
 * 
 * @author Jan Bernitt
 *
 * @param  Type of the thread local value
 */
public class IterableThreadLocal extends ThreadLocal implements Iterable> {

    private final Map entries;
    private final Supplier initialValue;

    public IterableThreadLocal(Supplier initialValue) {
        this.initialValue = initialValue;
        this.entries = synchronizedMap(new WeakHashMap<>());
    }

    @Override
    protected T initialValue() {
        T value = initialValue != null ? initialValue.get() : super.initialValue();
        entries.put(Thread.currentThread(), value);
        return value;
    }

    @Override
    public void set(T value) {
        super.set(value);
        entries.put(Thread.currentThread(), value);
    }

    @Override
    public void remove() {
        super.remove();
        entries.remove(Thread.currentThread());
    }

    @Override
    public Iterator> iterator() {
        return entries.entrySet().iterator();
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy