Reputation: 387
I am about to write my first multi threaded Java application. The task basically is to create sales report for a set of products; the products and the inputs to the report generator class are completely independent.
I believe we can create multiple threads (I would like to control the number of threads to create from a properties files based on number of CPUs in the target machine). to use them generate reports asynchronously. Currently this is what I do in my single threaded program.
I wish Java gurus give me some inputs on the design. Thanks in advance.
Structure of Report Generator class
public class SalesReportGenerator
{
//Variables
public Report prepareReport(Product prod){
//Implementation
}
//Helper methods used by SalesReportGenerator.prepareReport
}
My current implementation which I would like to perform in a multi threaded approach.
public class ReportCreater
{
public static void main(String args[]){
ListProducts listProd = new ListProducts(); //Getting product list
ArrayList products = listProd.getProductAsArrayList(); //To store list of products
ArrayList reports = new ArrayList(); //To store reports
SalesReportGenerator salesGen = new SalesReportGenerator();
Report tempReport = null;
for (int i;i<products.size() ;i++ )
{
tempReport = salesGen.prepareReport(products.get(i));
reports.add(tempReport);
}
//At this point I will have reports for all the producst
//which I can use for processing, further reporting/saving.
}
}
I would like to know what is the best way to first create a set of threads and make them pick a product and generate report.
Thanks.
Upvotes: 1
Views: 1076
Reputation: 27174
What you need is a class that creates a thread pool and distribute the report generation tasks among them. Java already provides such a class. It is called ExecutorService. You define a task as a Runnable
and pass it to an object of ExecutorService
. When you create this object, you should specify the size of the thread pool. If the tasks are CPU intensive, you might want to limit this size to NumberOfProcessors + 1
. (See this example on how to determine the value of NumberOfProcessors
). You submit as many tasks as you want to this object and it will manage how they get executed by the available threads. There are many tutorials on the web that shows you how to use this class.
Upvotes: 2