Multithreading in java
It says multiple tasks can be done at a time but actually its not exactly like that.
It will keep the cpu idle time less. Because cpu will have a responsibility to execute many threads if we
Use multithreading.
If its single threaded application then it might keep the cpu idle for some time and hence lowers the performance.
Lets see the same through example.
Requirement
Read multiple files from a location and write the content of each file to the same destination file by appending each time.
i have kept total 3000 files in the source location to read and i will create one thread to read and write one file content in multithreading scenario whereas in single thread scenario for loop iterates 3000 times to read and write 3000 files.
Lets use single threaded program
- package com.kb;
- import java.io.BufferedReader;
- import java.io.BufferedWriter;
- import java.io.File;
- import java.io.FileNotFoundException;
- import java.io.FileReader;
- import java.io.FileWriter;
- import java.io.IOException;
- public class SingleThreadWriteToFile {
- public static void main(String[] args) {
- long startTime = System.nanoTime();
- File dir = new File("E:\\java\\sample files");
- File destination = new File("E:\\java\\sample files\\Destination.txt");
- File[] files = dir.listFiles();
- String content;
- for (File file : files) {
- content = readFromFile(file.getAbsolutePath());
- writeToFile(destination,content);
- }
- long stopTime = System.nanoTime();
- System.out.println("Total execution time is "+(stopTime - startTime));
- }
- private static void writeToFile(File file,String content) {
- try {
- BufferedWriter writer = new BufferedWriter(new FileWriter(file,true));
- writer.write(content);
- writer.flush();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- static String readFromFile(String filename){
- StringBuffer content = new StringBuffer();
- try {
- String text;
- BufferedReader reader = new BufferedReader(new FileReader(filename));
- while((text = reader.readLine())!=null){
- content.append(text);
- content.append("\n");
- }
- } catch (FileNotFoundException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- return content.toString();
- }
- }
package com.kb; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class SingleThreadWriteToFile { public static void main(String[] args) { long startTime = System.nanoTime(); File dir = new File("E:\\java\\sample files"); File destination = new File("E:\\java\\sample files\\Destination.txt"); File[] files = dir.listFiles(); String content; for (File file : files) { content = readFromFile(file.getAbsolutePath()); writeToFile(destination,content); } long stopTime = System.nanoTime(); System.out.println("Total execution time is "+(stopTime - startTime)); } private static void writeToFile(File file,String content) { try { BufferedWriter writer = new BufferedWriter(new FileWriter(file,true)); writer.write(content); writer.flush(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } static String readFromFile(String filename){ StringBuffer content = new StringBuffer(); try { String text; BufferedReader reader = new BufferedReader(new FileReader(filename)); while((text = reader.readLine())!=null){ content.append(text); content.append("\n"); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return content.toString(); } }
Output is
Now lets use multithreading to the above program.
Here how it goes
- package com.kb;
- import java.io.BufferedReader;
- import java.io.BufferedWriter;
- import java.io.File;
- import java.io.FileNotFoundException;
- import java.io.FileReader;
- import java.io.FileWriter;
- import java.io.IOException;
- public class MultithreadingWriteToFile {
- public static void main(String[] args) {
- Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
- long startTime = System.nanoTime();
- File dir = new File("E:\\java\\sample files");
- File destination = new File("E:\\java\\sample files\\DestinationMultiThread.txt");
- File[] files = dir.listFiles();
- for (File file : files) {
- Writer w1 = new Writer(file, destination);
- Thread t = new Thread(w1);
- t.setPriority(Thread.MAX_PRIORITY);
- t.start();
- }
- long stopTime = System.nanoTime();
- System.out.println("Total execution time is "+(stopTime - startTime));
- }
- }
- class Writer implements Runnable{
- File source;
- File destination;
- public Writer(File source,File destination) {
- this.source = source;
- this.destination = destination;
- }
- @Override
- public void run() {
- String content;
- content = readFromFile(source.getAbsolutePath());
- writeToFile(destination,content);
- }
- private static void writeToFile(File file,String content) {
- try {
- BufferedWriter writer = new BufferedWriter(new FileWriter(file,true));
- writer.write(content);
- writer.write("file content written");
- writer.flush();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- static String readFromFile(String filename){
- StringBuffer content = new StringBuffer();
- try {
- String text;
- BufferedReader reader = new BufferedReader(new FileReader(filename));
- while((text = reader.readLine())!=null){
- content.append(text);
- content.append("\n");
- }
- } catch (FileNotFoundException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- return content.toString();
- }
- }
package com.kb; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class MultithreadingWriteToFile { public static void main(String[] args) { Thread.currentThread().setPriority(Thread.MIN_PRIORITY); long startTime = System.nanoTime(); File dir = new File("E:\\java\\sample files"); File destination = new File("E:\\java\\sample files\\DestinationMultiThread.txt"); File[] files = dir.listFiles(); for (File file : files) { Writer w1 = new Writer(file, destination); Thread t = new Thread(w1); t.setPriority(Thread.MAX_PRIORITY); t.start(); } long stopTime = System.nanoTime(); System.out.println("Total execution time is "+(stopTime - startTime)); } } class Writer implements Runnable{ File source; File destination; public Writer(File source,File destination) { this.source = source; this.destination = destination; } @Override public void run() { String content; content = readFromFile(source.getAbsolutePath()); writeToFile(destination,content); } private static void writeToFile(File file,String content) { try { BufferedWriter writer = new BufferedWriter(new FileWriter(file,true)); writer.write(content); writer.write("file content written"); writer.flush(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } static String readFromFile(String filename){ StringBuffer content = new StringBuffer(); try { String text; BufferedReader reader = new BufferedReader(new FileReader(filename)); while((text = reader.readLine())!=null){ content.append(text); content.append("\n"); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return content.toString(); } }
Output is
See the time difference between each output is
396687651 nano seconds.
This is how multithreading helps us to achieve the performance.
how to delete the files from source once copying is done. – in Multithreading
Hi,
Good post, but I was wondering why the Reader and Writer were never closed. Isn’t it a problem there?
Hi Ashok, Thanks for reading this post and your suggestion.
We should close the open resources always in finally block, i have not done it just because i was focusing on multi-threading concept. but in real time application , it is must and should that we have to close it.
I will update this post for the same.