What about ThreadLocal

My First Encounter With ThreadLocal

  • Problem: Find an efficient way to share dynamic configurable values in an application, without restarting the application.
  • Solution: Use ThreadLocal.

    At first, I have thought about loading the config values into system memory or the application context during the start-up phrase. However, if I need to change the values, then I would need to restart the application.

    Then, I think about reading these values from properties files or from database every time when I need to use it. But that is very inefficient.

    Well, ThreadLocal seems to be prefect for this type of jobs.

FAQs of ThreadLocal

  • What is the benefit of using ThreadLocal?

    An easier thread-safe way to manage shared variables in a thread-scope (sort of like web session-scope/request-scope) without explicitly passing the variables in method signature.
  • Why not that many people know about ThreadLocal?

    Well, many developers do know about ThreadLocal, since it has been introduced in Java 1.2. However, not that many use it because of the performance issue of using it in Java 1.2. Nevertheless, the performance of ThreadLocal has gradually improved in each newer version of Java.
  • What is a thread-local variable?

    Each thread that accesses a thread-local variable (via the get or set method) has its own, independently initialized copy of the variable.
  • Synchronize vs. ThreadLocal

    For safely sharing the access to certain objects (resources/variables), using ThreadLocal or synchronizing the objects are both fine. However, such objects are usually more expensive to create than to use. One good example would be JDBC connection. Furthermore, this is why pooling might not be a better solution than using ThreadLocal, especially when pool implementations must synchronize the pool data structure to maintain integrity.
  • What about memory leak issue with ThreadLocal?

    When a thread is terminated, all of its ThreadLocal instances are subject to be cleaned by garbage collection, unless other references to these copies exist. Also, please be aware that some application platforms/environments use a Thread pool. That is, the thread might never die, and the ThreadLocal instances would stay in memory and would not go away. Therefore, it is always a good practice that when you no longer need these ThreadLocal instances, please set them to null or call the remove() method.
  • Static and ThreadLocal

    In Java, ThreadLocal is a class, and static is a modifier that can be used on variables, methods, and classes. Making a ThreadLocal variable static and private is a way to ensure the variable’s integrity per-thread.
  • Volatile and ThreadLocal

    Volatile is a modifier that defines the way on how a variable be accessed and stored in memory. And, it is generally ignored by most JVM implementation. ThreadLocal is a class, which provides a mechanism on how to share data among different modules/classes/instances in a single thread. It has nothing to do with memory access requirement.
  • Would each child thread need to call the initialValue() or set() method, even it just needs to read same ThreadLocal variable from the parent?

    In that scenario, please use the subclass InheritableThreadLocal. Furthermore, if the goal is to read, then use the ThreadLocal or InheritableThreadLocal for immutable objects only. Also, with InheritableThreadLocal, the data is now shared with multiple threads, therefore, stateful objects like JDBC connections should not be declared as InheritableThreadLocal.

Other Resources

Java IO Demystified

Many Java developers feel the Java IO features are confusing, and overwhelming. I felt the same when I first used the Java IO packages. Gradually, I have tried to work my way of the mysteries. Following summary is a bit over general, but has helped me to understand the Java IO packages.

The Basics

The java.io package contains a class for random access files, but mainly, the classes in the package are for handling data-stream. There are two main types of data-streams: byte stream and character stream. There are various sources or destinations that the stream goes in and out. Some of the common source or destinations are file, string, threads, and serialize objects.

Naming

For byte streams, the classes have the names related to InputStream and OutputStream; for character streams, the classes have the names related to Reader and Writer.

The Reader and Writer classes are really just byte streams with additional conversion from bytes to characters, with enhanced support on character encoding.

Subclasses are usually named for one of the following stream-data attributes:

  • the source/destination
  • the types
  • additional processing or filtering performed (operations)

The operations are accomplished through stream filters, which accept compatible object as a parameter to the constructor and manipulate/decorate the input stream with additional processing. These filters are created by extending the base filter classes, FilterInputStream, FilterOutputStream, FilterReader, or FilterWriter.

Examples of the naming:

Operations Source/Destination Stream types Classes names
read/write byte array (byte[]) byte ByteArrayInputStream, ByteArrayOutputStream
read/write char array (char[]) char CharArrayReader, CharArrayWriter
read/write file byte, char FileInputStream, FileOutputStream, FileReader, FileWriter
read/write string (StringBuffer) char StringReader, StringWriter
read/write thread (piped) byte, char PipedInputStream, PipedOutputStream, PipedReader, PipedWriter
buffering compatible stream byte, char BufferedInputStream, BufferedOutputStream, BufferedReader, BufferedWriter
read/write primitive types compatible stream byte DataInputStream, DataOutputStream
object serialization (read/write objects) compatible stream byte ObjectInputStream, ObjectOutputStream
Follow

Get every new post delivered to your Inbox.