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?