Sitemap
Nuwan Zen

Nuwan Zen

Sometimes A software Engineer, sometimes a support engineer, sometimes a devops engineer, sometimes a cloud engineer :D That’s how the this life goes!

Java ThreadLocal

1 min readMar 6, 2021

--

Allows us to store data individually per thread. when we want to use this value from a thread we only need to call a get() or set() method.

Press enter or click to view image in full size
public class Context {
private String userName;

public Context(String userName) {
this.userName = userName;
}
}

Lets consider context object for the user application,

public class User implements Runnable {

private static ThreadLocal<Context> tl = new ThreadLocal<>();
private Integer userId;
private UserRepository repo = new UserRepository();

@Override
public void run() {
String userName = repo.getUserNameForUserId(userId);
tl.set(new Context(userName));
System.out.println(userId + " is: " + tl.get());
}


}

we can test this

User firstUser  = new User(1);
User secondUser = new User(2);
new Thread(firstUser).start();
new Thread(secondUser).start();

We can see that each of the users has its own Context.

Get Nuwan Zen’s stories in your inbox

Join Medium for free to get updates from this writer.

We should be careful when using ThreadLocals and thread pools together. When application reuses threads from the pool if clean up tasks did take properly for the last use, this can give incorrect results. it’s possible to extend the ThreadPoolExecutor class and provide a custom implementation for beforeExecute() and afterExecute() methods to over come this issue.

Ref: https://www.baeldung.com/java-threadlocal

Read my other blogs:

--

--

Nuwan Zen
Nuwan Zen

Written by Nuwan Zen

Sometimes A software Engineer, sometimes a support engineer, sometimes a devops engineer, sometimes a cloud engineer :D That’s how the this life goes!