Devanshu Verma’s Post

🚀 30 Days of Java Interview Questions – Day 23 💡 Question: What is ThreadLocal in Java and how does it work internally? This is a rare and tricky question often asked in backend and multithreading interviews. 🔹 What is ThreadLocal? ThreadLocal is a class that provides thread-specific variables. Each thread has its own independent copy of the variable. 🔹 Why Use ThreadLocal? Used when you want to avoid sharing data between threads. Example use cases: • Database connections • User sessions • Transactions 🔹 How It Works Internally Each Thread has its own ThreadLocalMap Thread → ThreadLocalMap → (ThreadLocal, Value) So every thread stores its own value separately 🔹 Example ```java class Test { static ThreadLocal<Integer> threadLocal = new ThreadLocal<>(); public static void main(String[] args) { threadLocal.set(100); System.out.println(threadLocal.get()); // 100 } } ``` 🔹 Important Methods set(value) → store value get() → retrieve value remove() → remove value (important to prevent memory leaks) 🔹 Important Points • Each thread has its own copy • No synchronization required • Must call remove() to avoid memory leaks ⚡ Quick Summary • ThreadLocal → thread-specific storage • Internally uses ThreadLocalMap • Helps in thread isolation 📌 Interview Tip Mention this line to stand out: “ThreadLocal avoids synchronization by giving each thread its own copy of data.” Follow this series for more advanced Java interview questions. #java #javadeveloper #multithreading #threadlocal #codinginterview #backenddeveloper #softwareengineer #programming

  • graphical user interface, text, application, chat or text message

To view or add a comment, sign in

Explore content categories