jpl
jpl

Reputation: 367

How to make a Thread from its ExecutorService communicate with a Runnable?

I'm currently using ExecutorService for parsing files:

ExecutorService service = Executors.newFixedThreadPool(10);

and later:

service.submit(new FileParser(file));

However the tools used to parse the files require an initialization which takes quite long. I'd like to perform the initialization only once per thread (not once for all because initialization parameters are not thread-safe), and then to perform only the parsing in the submitted runnable.

I saw that ThreadFactory can be used to provide my own threads to the executor, so I could initialize my parameters this way:

public class MyThreadFactory implements ThreadFactory {
    public Thread newThread(Runnable r) {
        return new MyThread(); // Initialization part inside the constructor
    }
}

However then I have no idea on how to provide the new file to parse to the thread... Any idea?

Thanks

Upvotes: 0

Views: 353

Answers (1)

sodik
sodik

Reputation: 4683

You can use ThreadLocal variable for this initialization. During each execution, you can check if you have executed initialization for current thread and then use it for storing whatever you need.

Upvotes: 1

Related Questions