04
Mar

InheritableThreadLocal – share variables from Parent to child threads

InheritableThreadLocal class is a subclass of ThreadLocal. Instead of each thread having its own value inside a ThreadLocal, the InheritableThreadLocal grants access to values to a thread and all child threads created by that thread.

InheritableThreadLocal -  share variables from Parent to child threads 
=========================================================================

Step 1: Create your custom Thread implementation

public class ThreadOne extends Thread {

	private InheritableThreadLocal<String> itl;

	public ThreadOne(InheritableThreadLocal<String> itl) {
		this.itl = itl;
	}
	
	public void run() {
		System.out.println("From child => "+itl.get());
	}
}


Step 2:  use main() to pass values from main thread

public class MainClass {

	public static void main(String[] args) {
		InheritableThreadLocal<String> itl = new InheritableThreadLocal<>();
		itl.set("From main");
		
		ThreadOne obj = new ThreadOne(itl);
		Thread t = new Thread(obj);
		t.start();

	}

}


Output:
From child => From main