views:

97

answers:

4

The following class shows something similar to a real use case. It returns always the same instance for the same thread.

public class LookingForName {

    private static final ThreadLocal<Something> threadLocal = 
        new ThreadLocal<Something>(){
            @Override
            protected Something initialValue() {
                return getSomethingSpecial(); // not relevant
            }
        };

    /**
     * @return always the same instance of "Something" for the current thread.
     */
    public static Something getInstance() {
        return threadLocal.get();
    }

}

How would you call it? Is it a "factory"? A "value holder"? "ThreadLocalStore"?

+3  A: 

Not a factory. looks like a singleton. The idea of the factory is to CREATE objects dirrived on a based class.

Arseny
Yes, but a "per thread singleton".
deamon
A: 

getInstance() is most definitely a factory method.

Someone might have compe up with a cool name for the entire per-thread-pseudo-singleton, but since it's too rare a case to be widely relevant, there is no value in having it. "Per-thread singleton" sounds like the best option to me.

Michael Borgwardt
+6  A: 

Some simply called it the ThreadLocal Pattern. Another known name is Thread-local Storage (TLS).

Andreas_D
I will go with `ThreadLocalSomething` since it describes pretty good what is going on.
deamon
A: 

Hi,

For complete reference of Factory Method design pattern and other related pattern, refer this article,

http://www.codinguide.com/2010/04/factory-pattern.html

Regards,

Interperator