Search code examples
javathread-local

How to reduce the verbose redundancy of java thread local


I have a class and I want declare a private member which is a thread local dictionary. So this is how it looks...

private static ThreadLocal<HashMap<Integer, Measurement>> measurements = 
        new ThreadLocal<HashMap<Integer, Measurement>>() 
{
    @Override protected HashMap<Integer, Measurement> initialValue()
    {
        return new HashMap<Integer, Measurement>();
    }

};

As you can see I have to type HashMap<Integer, Measurement> an absurd number of times. Is there any way to make this more succinct?


Solution

  • How about this ?

    private static ThreadLocal<HashMap<Integer, Measurement>> measurements = ThreadLocal.withInitial(HashMap::new);