4

Which method is more acceptable to access to a Non Thread Safe Object ?

using ThreadLocal objects :

static final ThreadLocal<NonThreadSafeParser> PARSER_THREAD_LOCAL = new ThreadLocal<NonThreadSafeParser>() {
    @Override
    protected NonThreadSafeParser initialValue() {
        return new NonThreadSafeParser();
    }
};

void parse(String input) {
    PARSER_THREAD_LOCAL.get().parse(input);
}

using a Concurrent Object Pool :

static final ConcurrentObjectPool<NonThreadSafeParser> PARSER_POOL = new ConcurrentObjectPool<>();

void parse(String input) {
    NonThreadSafeParser parser = PARSER_POOL.borrow();
    try {
        parser.parse(input);
    } finally {
        PARSER_POOL.release(parser);
    }
}

or other methods that you want to offer?

Important factors are :

  • Performance
  • Memory Usage
  • Garbage Collection

Generally, what are the Pros and Cons for each method?

Is there any noticeable difference between them?

Thanks.

EDIT :

An example of Concurrent Object Pools used by Kryo.

FaNaJ
  • 1,329
  • 1
  • 16
  • 39

3 Answers3

5

The obvious difference is of course that you have either a pool of objects, or a dedicated object per thread. This has various consequences such as ThreadLocals can be fully stateful since they're only used by a single thread. Pooled objects can be stateful, but only during the time they're checked out by a thread.

Some people think ThreadLocals are evil and even if they're not, they still require you to be a smart cookie when using them. Object pool pitfalls and advantages depend a lot on the actual objects being stored inside.

So in conclusion: it depends and it's somewhat opinion based. Once again we have a software development question that doesn't have an absolute answer, even though people love to think that we're dealing with an exact science.

Kayaman
  • 72,141
  • 5
  • 83
  • 121
1

In general, I would use

ThreadLocal - if that object belongs to that thread only but can't be private and need to be accessed across layers. It could be context related to the current thread.

ThreadPool - when I need to share limited resources or need to synchronize communication between multiple threads.

Pranalee
  • 3,389
  • 3
  • 22
  • 36
1

A rough rule of thumb may be how "long" of a lease each thread would generally have on those objects. If threads should hold onto these objects for (close to) the whole time they're actively running anyway, a ThreadLocal<> may be the way to go. On the other hand, if these objects are to be used only briefly or intermittently compared to the whole thread's lifetime, then object pooling may be the way to go.

ManRow
  • 1,563
  • 4
  • 21
  • 40