I'm mainly posting this so I have a copy on the blog, but I figured it may be of interest to someone out there as well. It may be old hat to folks who deal with multithreading all the time, but since I don't it was pretty interesting.
I wanted a quick and easy way to spawn multiple threads to populate a list of results. I didn't have any big concurrency concerns as I was dealing with some pretty simple objects that weren't being modified inline or anything - just needed to process them and wanted to try it with multiple threads (which turned out to not be any better performance, but that's beside the point).
Here's an example of how it turned out:
List<MyReturnObject> results = new ArrayList<MyReturnObject>;
// Create a list of 'Callable' objects that will perform the operation and return the desired object
// (in this case call the 'performSomeLogic' method)
List<Callable<DocService>> callables = new ArrayList<Callable<DocService>>();
for (final SomeReferenceObject refObj: refObjects) {
callables.add(new Callable<MyReturnObject>()
{
@Override
public MyReturnObject call() throws Exception
{
return performSomeLogic(refObj);
}
});
}
// Create an ExecutorService which will manage the threads AND manage waiting til all threads are done
// before allowing a result to be returned (e.g. I don't have to keep checking the threads to see if
// they're done yet).
ExecutorService es = Executors.newFixedThreadPool(5);
try
{
List<Future<DocService>> results = es.invokeAll(list);
for(Future<DocService> result: results) {
// This will actually wait for the related thread to be complete before returning the value
resultList.add(result.get());
}
}
catch (Exception e)
{
e.printStackTrace();
}
In the end I didn't use it but I'm going to store it away for future reference. Seemed like a real simple way to break up work.