I am trying to build a utility library which adds tasks in a ThreadPoolExecutor queue. I want to accept a list/array of objects, a callable function, and a list of function arguments to be passed in the callable function. Now I want to pass these list or arguments in the function call I am making from the callable interface, but Callable interface only has one function which does not take any arguments.
Can someone help me in redesigning the structure? I want clients of this library to call one single function with above-mentioned arguments and the library should handle everything.
My Current class looks like this:
public class ThreadPoolExecutorUtils {
private ExecutorService executorService;
/**
* Initialize Executor service with given number of threads
* @param threadCount : number of threads on the thread pool
*/
public ThreadPoolExecutorUtils(int threadCount) {
executorService = Executors.newFixedThreadPool(threadCount);
}
/**
* Add the task to the queue of current threadpool executor
* @param callableFunc: Function to be called from every thread
*/
public <T> void scheduleTask(Callable<T> callableFunc) {
executorService.submit(new Runnable() {
@Override
public void run() {
try {
callableFunc.call();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Blocks until all tasks have completed execution after a shutdown
* request, or the timeout occurs, or the current thread is
* interrupted, whichever happens first.
* @param timeOutSeconds : The maximum time in seconds to wait
*/
public void awaitCompletion(int timeOutSeconds) {
executorService.shutdown();
try {
executorService.awaitTermination(timeOutSeconds, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
executorService.shutdownNow();
}
}
}
In this, the client has to make the object of ThreadPoolExecutorUtils and iterate over its list of task and pass individual callable function. I want to abstract that for client.
Have you considered anything from java.util.function
package. I think its more appropriate for your use case than Callable
, something like BiConsumer
or BiFunction
.
Since Callable
output is not used in your example code i dont see the need to use it.