I have created the below application to test the ExecutorService
. I have one Reader
thread which reads from a file. The string read(upto 2 lines) is passed recurrently to a writer
task which is responsible for printing the string onto the console. I submit this task to an executor
pool
where the worker
threads execute the task. How do I check whether this method is indeed faster as compared to using say only one thread/one process doing the reading and writing both by itself?
public class ClientTest {
ExecutorService e= Executors.newFixedThreadPool(2);
static ClientTest c = new ClientTest();
public static void main(String args[])
{
Thread reader=new Thread() {
public void run() {
BufferedReader br=null;
int n=0;
try {
br = new BufferedReader(new FileReader("C:\\Users\\JOHHNY\\Desktop\\Sample.txt"));
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append("\n");
n++;
if(n%2==0) {
c.write(sb);
Thread.sleep(1000);
sb.setLength(0);
}
line = br.readLine();
}
}
catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
finally {
try {
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
};
reader.start();
}
private void write(final StringBuilder sb) {
e.execute(new Runnable() {
public void run() {
System.out.println(Thread.currentThread().getName()+" "+sb.toString());
}
});
}
}