Esteban S
Esteban S

Reputation: 1919

Java synchronize an external file

Are there anyway to syncronize the reading and writing of a file between two process in Java?

I found FileLock, with this I can lock a file while it is writing, but I need to have a process polling for the reading, that is not efficient. I would like to simulate the semaphores, to make it efficient:

class Process<E> {
  private E e;

  private final Semaphore read = new Semaphore(0);
  private final Semaphore write = new Semaphore(1);

  public final void write(final E e) {
    write.acquire();
    this.e = e;
    read.release();
  }

  public final E read() {
    read.acquire();
    E e = this.e;
    write.release();
    return e;
  }
}

Are there anyway to do it with Filelock or other class?

Thanks in advance.

Upvotes: 1

Views: 52

Answers (1)

Joop Eggen
Joop Eggen

Reputation: 109547

Forgotten about Java pipes? Like PipedInputStream and PipedOutputStream need to use different threads to efficiently exchange data.

Upvotes: 1

Related Questions