Question: i have 20 threads that write with the println() function on a file called results.txt. How can i synchronize them all?

I note every time my program run i have different number of lines of text in results.txt.

Thank you.

Answer: 
Access the file through a class that contains a [synchronized method](http://docs.oracle.com/javase/tutorial/essential/concurrency/syncmeth.html) to write to the file. Only one thread at a time will be able to execute the method.

I think that Singleton pattern would fit for your problem:

```
package com.test.singleton;

public class Singleton {
    private static final Singleton inst= new Singleton();

    private Singleton() {
        super();
    }

    public synchronized void writeToFile(String str) {
        // Do whatever
    }

    public static Singleton getInstance() {
        return inst;
    }

}

```

Every time you need to write to your file, you only would have to call:

```
Singleton.getInstance().writeToFile("Hello!!");

```
Duplicate question ... duplicate answer. [As I said here:](https://stackoverflow.com/a/9976133/823393)

If you can hold your file as a `FileOutputStream` you can lock it like this:

```
FileOutputStream file = ...
....
// Thread safe version.
void write(byte[] bytes) {
  try {
    boolean written = false;
    do {
      try {
        // Lock it!
        FileLock lock = file.getChannel().lock();
        try {
          // Write the bytes.
          file.write(bytes);
          written = true;
        } finally {
          // Release the lock.
          lock.release();
        }
      } catch ( OverlappingFileLockException ofle ) {
        try {
          // Wait a bit
          Thread.sleep(0);
        } catch (InterruptedException ex) {
          throw new InterruptedIOException ("Interrupted waiting for a file lock.");
        }
      }
    } while (!written);
  } catch (IOException ex) {
    log.warn("Failed to lock " + fileName, ex);
  }
}

```