Multithreading write to files in java

I am trying to achieve the following things:

  1. File with same name should be modified by only one thread at a current time.
  2. If file is having different name then multiple threads could write to different files at the same time.

However, I am unable to achieve this. Moreover, the print statements appears in random fashion. That’s why it becomes difficult to know whether I am giving input for file name or file content.

public class Sample implements Runnable {

    public void run() {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                System.in));
        String name = null;

        synchronized (this) {
            System.out
                    .println("File to modify");

            try {
                name = reader.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            } 

        }
        readContent(name);
    }

    public synchronized void writeDocument(String name, String content) {

        PrintWriter out = null;
        synchronized (name) {
            try {

                out = new PrintWriter(new BufferedWriter(new FileWriter(name,
                        true)));
                out.flush();
                out.print(content);

            } catch (IOException e) {
                System.out.println("IOException, something went wrong");
            } finally {

                out.close();
            }
        }

    }

    public void readContent(String name) {

        String content = null;
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                System.in));

        try {
            System.out.println("Enter the file content "
                    + Thread.currentThread().getName() + ":");
            content = reader.readLine();

        } catch (IOException e) {
            System.out.println("IOException, something went wrong");
        } 

        writeDocument(name, content);
    }
}


Source: java

Leave a Reply