I have a function that serially (single-threaded-ly) iterates through a directory of files, changing all tab indentation to three-space indentation.
I'm using it as my first attempt at multi-threading. (Am most of the way through Java Concurrency in Practice...surprised it's eight years old now.)
In order to keep it's current single-threaded functionality, but add in the additional possibility of multi-threading, I'm thinking of changing the function to accept an additional Executor parameter, where the original single-threaded function would now be a call to it, passing in a single threaded executor.
Is this an appropriate way to go about it?
One way is as @Victor Sorokin suggests in his answer: wrap the processing of every file in a Runnable
and then either submit to an Executor
or just invoke run()
from the main thread.
Another possibility is to always do the same wrapping in a Runnable
and submit it to an always-given Executor
.
Whether processing of each file is executed concurrently or not would depend on the given Executor
's implementation.
For parallel processing, you could invoke your function passing it i.e. a ThreadPoolExecutor
as an argument, whereas for sequential processing you could pass in a fake Executor
, i.e. one that runs submitted tasks in the caller thread:
public class FakeExecutor implements Executor {
@Override
public void execute(Runnable task) {
task.run();
}
}
I believe this way is the most flexible approach.