1
votes

I have a non thread-safe object that I use when executing a Runnable. However this object is expensive to create and creating them in each Runnable causes too much overhead. Instead, I want ThreadPoolExecutor to use my custom thread which has an extra field and share that field between Runnable instances running in same thread.

I created I custom Thread class that has my custom field. I create ThreadPoolExecutor like that:

executor = new ThreadPoolExecutor(5, 50, 0, TimeUnit.MILLISECONDS, new LinkedBlockingQueue(), new CustomThreadFactory())

CustomThreadFactory creates my custom Thread in newThread(Runnable r) method. However, in order to use the field in Runnable instances, I also needed to create my custom Runnable which takes the reference of my non-thread object and save it in order to use in run() method.

However since ThreadPoolExecutor uses Workers in order to execute Runnable instances, I couldn't be able to invoke my non thread-safe object to Runnable instances. Is there any convenient way to do such thing using ThreadPoolExecutor or do I need to create custom ThreadPoolExecutor?

1
You should use a ThreadLocal rather than using custom threads. docs.oracle.com/javase/7/docs/api/java/lang/ThreadLocal.html - JB Nizet

1 Answers

0
votes

Just so that this question can be marked as answered:

If there is no other reason for you to use a custom thread factory (like giving custom thread names), then a ThreadLocal is the preferred way. It fits your description of what you want to achieve exactly.