-1

I want thread 1 to write in a text file and then thread 2 write another thing, but thread 2 will always overwrite what thread 1 wrote

how can i prevent this using Synchronization(if possible) ?

MultiThreadMain.java:

public class MultiThreadMain {
    public static void main(String[] args) throws InterruptedException {
        ReadFile thread1 = new ReadFile();
        ReadFile thread2 = new ReadFile();
        thread1.start();
        thread2.start();
        thread1.join();
        thread2.join();
    }
}

ReadFile.java:

public class ReadFile extends Thread {    
    synchronized void ReadTxtFile() throws IOException {
        FileWriter write = new FileWriter("filelocation");
        write.write("hello");
        write.close();
    }    
    @Override
    public void run() {
        try {
            ReadTxtFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
Janez Kuhar
  • 3,705
  • 4
  • 22
  • 45
  • 2 will always overwrite what thread 1 wrote? In which case, thread 1 can have an item in a file? Can you create some examples? – Akif Hadziabdic Apr 01 '21 at 18:15
  • What are you expecting it to do? Since you are starting thread 1 first, it's highly possible (almost always) that thread 2 will overwrite what thread 1 did. But it looks like you want to append the text rather than replacing the text. Even then, the text that will be written is not always guaranteed to be in the same order. – Arun Gowda Apr 01 '21 at 18:17
  • 1 write "hello", 2 write "hi", 1 write "hello" file will contains: "hello" or "hellohihello"? – Akif Hadziabdic Apr 01 '21 at 18:23
  • 1
    1 write hello, 2 also write hello but when i go to the file i see only one word of hello, not two, i dont know if im doing it wrong though – THE_TERRIBLE _ Apr 01 '21 at 18:32

1 Answers1

0

You should use writer.append(...) instead of writer.write(...), which will append the contents to the file.

Also make sure to make the method name initials in small case as a good practice of code.

Also make sure to close the writer in finally block, so that it gets properly close in case of any exception.

EDIT:

As pointed out by @janezKuhar, .write() and .append() are typically same. You can check this in JavaDocs - https://docs.oracle.com/javase/7/docs/api/java/io/FileWriter.html

Now to append the contents to the file, you need must need to pass boolean parameter while creating instance of FileWriter, to make it appendable, somewhat like this - FileWriter writer = new FileWriter("filename", true);

More ways to write to a file in Java: https://stackoverflow.com/a/1625263/3709922

Jignesh M. Khatri
  • 1,407
  • 1
  • 14
  • 22
  • Glad to help. You can mark this answer as accepted, so that if someone comes to this question to find a solution to their similar issue, they can find answer easily. – Jignesh M. Khatri Apr 01 '21 at 18:41
  • From [Writer#append()](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/io/Writer.html#append(java.lang.CharSequence)): *An invocation of this method of the form `out.append(csq)` behaves in exactly the same way as the invocation `out.write(csq.toString())`*. – Janez Kuhar Apr 01 '21 at 19:20
  • *"Also make sure to close the writer in finally block"* ... as of Java 7, the preferred way to close resources whose classes implement the `Autocloseable` interface is to declare the resources in a *try-with-resources* block. The *try-finally* idiom is more tricky to use correctly, particularly when multiple resources must be closed. – scottb Apr 02 '21 at 04:11
  • @scottb Anyways you need to safely close the resource after it is used. Whether you close it in finally block or try-with-resource block, doesn't matter as such on implementation level. Its just you save writing finally block and few other close statements with try-with-resource block. Fundamentals always remain same :) – Jignesh M. Khatri Apr 02 '21 at 04:33
  • @JigneshM.Khatri: *"Fundamentals always remain same"* My agreement with that position is implicit in my comment. Rather, my comment speaks to the error-proneness and difficulty that arises when using *try-finally* when there is more than one resource to close. The preferred solution for this circumstance in Java 7 or later is to use *try-with-resources*. – scottb Apr 02 '21 at 19:03