1+ package es .jea .processor ;
2+
3+ import java .util .concurrent .ExecutorService ;
4+ import java .util .concurrent .Executors ;
5+ import java .util .concurrent .TimeUnit ;
6+
7+ /**
8+ * Main class of the Data Processing function-
9+ */
10+ public class DataProcessingFramework {
11+ private static final long TIMEOUT =20L ;
12+ private ExecutorService executorService ;
13+ private DataReader reader ;
14+ private ResultWriter writer ;
15+ private int threads ;
16+ /**
17+ * Class Constructor.
18+ *
19+ * @param reader Reader to get the values to process.
20+ * @param writer Writer where to store the results.
21+ * @param threads Number of threads to perform the parallel processing.
22+ */
23+ public DataProcessingFramework (DataReader reader , ResultWriter writer , int threads ){
24+ this .reader = reader ;
25+ this .writer = writer ;
26+ this .threads = threads ;
27+ executorService = Executors .newFixedThreadPool (threads );
28+ }
29+
30+ /**
31+ * Start the processing of Data.
32+ */
33+ public void start (){
34+ reader .open ();
35+ writer .open ();
36+ for (int i = 0 ; i < this .threads ; i ++ ){
37+ executorService .execute (new Processor (reader , writer ));
38+ }
39+ }
40+
41+
42+ /**
43+ * Wait to the end of the computation.
44+ *
45+ * @throws InterruptedException
46+ */
47+ public void awaitTermination () throws InterruptedException {
48+ executorService .shutdown ();
49+ while (!executorService .isTerminated ()){
50+ executorService .awaitTermination (TIMEOUT , TimeUnit .SECONDS );
51+ }
52+
53+ }
54+
55+ /**
56+ * Executed the data processing funtion:
57+ * @param args Array of arguments expected: InputFile, OutputFile, number of threads.
58+ */
59+ public static void main (String [] args ) {
60+ if (args .length != 4 ){
61+ System .err .println ("Incorrect number of arguments <inputFile> <outputFile> <numThreads>" );
62+ System .exit (1 );
63+ }
64+ String inputFile = args [1 ];
65+ String outputFile = args [2 ];
66+ int threads = Integer .parseInt (args [3 ]);
67+ DataProcessingFramework dpf = new DataProcessingFramework (new CSVDataReader (inputFile ), new CSVResultsWriter (outputFile ), threads );
68+ System .out .println ("Starting processing of " + inputFile );
69+ dpf .start ();
70+ try {
71+ dpf .awaitTermination ();
72+ } catch (InterruptedException e ) {
73+ System .err .println ("Executor interrupted" );
74+ }
75+ System .out .println ("Processing finished" );
76+ }
77+ }
0 commit comments