How to run different methods parallely
java, multithreading, parallel-processing
Solution
Do something like this:
- For each method, create a Callable object that wraps that method.
- Create an Executor (a fixed thread pool executor should be fine).
- Put all your Callables in a list and invoke them with the Executor.
Here's a simple example:
public void testThread()
{
//create a callable for each method
Callable<Void> callable1 = new Callable<Void>()
{
@Override
public Void call() throws Exception
{
method1();
return null;
}
};
Callable<Void> callable2 = new Callable<Void>()
{
@Override
public Void call() throws Exception
{
method2();
return null;
}
};
Callable<Void> callable3 = new Callable<Void>()
{
@Override
public Void call() throws Exception
{
method3();
return null;
}
};
//add to a list
List<Callable<Void>> taskList = new ArrayList<Callable<Void>>();
taskList.add(callable1);
taskList.add(callable2);
taskList.add(callable3);
//create a pool executor with 3 threads
ExecutorService executor = Executors.newFixedThreadPool(3);
try
{
//start the threads and wait for them to finish
executor.invokeAll(taskList);
}
catch (InterruptedException ie)
{
//do something if you care about interruption;
}
}
private void method1()
{
System.out.println("method1");
}
private void method2()
{
System.out.println("method2");
}
private void method3()
{
System.out.println("method3");
}
Make sure each method does not share state (like a common mutable field in the same class) or you may get unexpected results. Oracle provides a good introduction to Java Executors. Also, this book is awesome if you are doing any kind of threading in java.
Problem
I have one java method which contains 5 different internal methods. For performance improvement, I want to call these methods parallely. e.g. run method1, method2, ... method5 parallel using thread. ``` private void getInformation() throws SQLException, ClassNotFoundException, NamingException { method1(); method2(); method3(); method4(); method5(); } ``` but all these 5 methods have different business logic.