title: How to synchronize multiple threads writing into a file
body: <p>I am using a <code>ExecutorService</code> to have multiple threads writing text into a file, but i cannot manage to synchronize the <code>run()</code> 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.</p>
  
  <pre><code>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();
      }
  }
  
  }
  </code></pre>