5 Pitfalls That Java Developers Will Step On

omgzui
Javarevisited
Published in
4 min readJan 30, 2023

--

Photo by Emile Perron on Unsplash

After working for so many years, I encountered several pits that I could not solve after several hours and finally found that it was caused by improper use. Let me share the five pits I encountered.

1. Using ThreadLocal in ThreadPool

If you create a ThreadLocal variable, a thread that accesses the variable will create a thread-local variable. Reasonable use of ThreadLocal can avoid thread safety issues.

However, if you use ThreadLocal in the thread pool, be careful. Your code may produce unexpected results. To give a very simple example, suppose we have an e-commerce platform, and users need to send an email confirmation after purchasing a product.

private ThreadLocal<User> currentUser = ThreadLocal.withInitial(() -> null);

private ExecutorService executorService = Executors.newFixedThreadPool(4);

public void executor() {
executorService.submit(()->{
User user = currentUser.get();
Integer userId = user.getId();
sendEmail(userId);
});
}

If we use ThreadLocal to save user information, there will be a hidden bug here. Because the thread pool is used, threads can be reused, so when using ThreadLocal to obtain user information, it is very likely to obtain other people’s information by mistake. You can use sessions…

--

--

omgzui
Javarevisited

A full stack engineer, with some medicinal knowledge, likes to read and share.