Swiftorial Logo
Home
Swift Lessons
AI Tools
Learn More
Career
Resources

Java FAQ: Top Questions

52. What is ThreadLocal in Java?

ThreadLocal in java.lang provides thread-local variables, where each thread has its own independent copy, avoiding synchronization for thread-confined data.

  • Usage: Create with ThreadLocal , set with set , get with get .
  • Memory Leaks: Must call remove to prevent leaks in thread pools.
  • Initial Value: Use withInitial for default values (Java 8+).
  • Use Case: Per-thread context, like user sessions or transaction IDs.