InheritableThreadLocal in Java

java.lang.InheritableThreadLocal<?>

This class extends ThreadLocal to provide inheritance of values from the parent thread to the child thread: when a child thread is created, the child receives initial values for all inheritable thread-local variables for which the parent has values. Normally the child's values will be identical to the parent's; however, the child's value can be made an arbitrary function of the parent's by overriding the childValuemethod in this class.

Note: During the creation of a new thread, it is possible to opt out of receiving initial values for inheritable thread-local variables.

Declaration

public class InheritableThreadLocal<T>
extends ThreadLocal<T> {

    public InheritableThreadLocal() {
    }

    protected T childValue(T parentValue) {
        return parentValue;
    }

    ThreadLocalMap getMap(Thread t) {
        return t.inheritableThreadLocals;
    }

    void createMap(Thread t, T firstValue) {
        t.inheritableThreadLocals =
new ThreadLocalMap(this, firstValue);
    }
}


Methods

1. InheritableThreadLocal<Object>()

java.lang.InheritableThreadLocal.InheritableThreadLocal<Object>()

Creates an inheritable thread local variable.

Approach

Java

package com.InheritableThreadLocal;

public class InheritableThreadLocal1 {
    public static void main(String[] args) {

        InheritableThreadLocal<?> inheritableThreadLocal =
new InheritableThreadLocal<>();

        System.out.println(inheritableThreadLocal);
    }
}

Output:

java.lang.InheritableThreadLocal@26f0a63f


2. childValue(T parentValue)

T java.lang.InheritableThreadLocal.childValue(T parentValue)

Computes the child's initial value for this inheritable thread-local variable as a function of the parent's value at the time the child thread is created.

This method is called from within the parent thread before the child is started.

This method merely returns its input argument and should be overridden if different behavior is desired.

Parameters: parentValue is the parent thread's value.

Returns: the child thread's initial value.


3. getMap(Thread t)

ThreadLocalMap java.lang.InheritableThreadLocal.getMap(Thread t)

Get the map associated with a ThreadLocal.

Parameters: t the current thread.

Returns: the map.


4. createMap(Thread t, T firstValue)

void java.lang.InheritableThreadLocal.createMap(Thread t, T firstValue)

Create the map associated with a ThreadLocal.

Parameters: t the current threadfirstValue value for the initial entry of the table.

No comments:

Post a Comment