HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaCritical

When and how should I use a ThreadLocal variable?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
howshouldandusevariablewhenthreadlocal

Problem

When should I use a ThreadLocal variable?

How is it used?

Solution

One possible (and common) use is when you have some object that is not thread-safe, but you want to avoid synchronizing access to that object (I'm looking at you, SimpleDateFormat). Instead, give each thread its own instance of the object.

For example:

public class Foo
{
    // SimpleDateFormat is not thread-safe, so give one to each thread
    private static final ThreadLocal formatter = new ThreadLocal(){
        @Override
        protected SimpleDateFormat initialValue()
        {
            return new SimpleDateFormat("yyyyMMdd HHmm");
        }
    };

    public String formatIt(Date date)
    {
        return formatter.get().format(date);
    }
}


Documentation.

Code Snippets

public class Foo
{
    // SimpleDateFormat is not thread-safe, so give one to each thread
    private static final ThreadLocal<SimpleDateFormat> formatter = new ThreadLocal<SimpleDateFormat>(){
        @Override
        protected SimpleDateFormat initialValue()
        {
            return new SimpleDateFormat("yyyyMMdd HHmm");
        }
    };

    public String formatIt(Date date)
    {
        return formatter.get().format(date);
    }
}

Context

Stack Overflow Q#817856, score: 923

Revisions (0)

No revisions yet.