Somasundaram Sekar
Somasundaram Sekar

Reputation: 5524

Using threadlocal to bind instance of a class to a thread

I have some difficulty in understanding the use of ThreadLocal in the below declaration. Does it mean, even though the instance is declared as static each thread will have it's own instance of DomainEventPublisher class

private static final ThreadLocal<DomainEventPublisher> instance = new ThreadLocal<DomainEventPublisher>() {
        protected DomainEventPublisher initialValue() {
            return new DomainEventPublisher();
        }
};

Upvotes: 0

Views: 145

Answers (1)

Jean Logeart
Jean Logeart

Reputation: 53819

Yes, that is exactly what ThreadLocal is for.

In your example, each thread will have a different instance of DomainEventPublisher

Upvotes: 1

Related Questions