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.