Fabio Olivetto
Fabio Olivetto

Reputation: 616

How to synchronize multiple threads writing into a file

I am using a ExecutorService to have multiple threads writing text into a file, but i cannot manage to synchronize the run() method and instead of having the proper line by line String i ask, i have a mixup of all the characters of the Strings because they write it at the same time.

import java.io.BufferedReader
...

class WriteDns implements Runnable {

File file;
String text;

WriteDns(File file, String text) {
    this.file = file;
    this.text = text;
}

public void run() {
    synchronized (this) {
        try (BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
                new FileOutputStream(file)))) {
            bw.write(turnDns() + "\n");
        } catch (IOException e) {
            System.out.println("Error");
        }
    }
}

public String turnDns() {
    int space = text.indexOf(' ');
    String ip = text.substring(0, space);
    String theRest = text.substring(space);
    String temp = ip;
    try {
        ip = InetAddress.getByName(ip).getHostName();
        if (ip == temp)
            return "NotFound " + theRest;
        return ip + " " + theRest;
    } catch (UnknownHostException e) {
        System.out.println("Error in change");
        return "-changeErr " + theRest;
    }
}

}

public class Main00 {

static File oldFile = new File("oldfile.txt");

public static void main(String[] args) {

    readLines();

}

public static void readLines() {
    try (BufferedReader br = new BufferedReader(new FileReader(oldFile))) {
        File f = new File("file.txt");
        ExecutorService service = Executors.newFixedThreadPool(10);
        for (String t = br.readLine(); t != null; t = br.readLine()) {
            service.execute(new WriteDns(f, t));
        }
        service.shutdown();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

}

Upvotes: 0

Views: 2291

Answers (1)

ldam
ldam

Reputation: 4595

You're synchronising on this but you're making a new instance of your thread worker for every thread, so each thread is locking on itself and never waiting for any other threads. You need to lock on an object that is visible to all threads, perhaps a static object or pass in a lock object when you instantiate your WriteDns.

With that said, having multiple threads open on one file is inherently prone to problems like you're experiencing, and you gain nothing from multiple threads writing since your bottleneck is your storage medium and not your processor. You should rather have multiple threads providing information/data to one dedicated writer thread that has exclusive access to the file you want to write to, as @FlorianSchaetz suggested.

Upvotes: 8

Related Questions