Java synchronize an external file

时间:2015-09-14 16:17:17

标签: java synchronization

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.

1 个答案:

答案 0 :(得分:1)

忘记了Java 管道?像PipedInputStreamPipedOutputStream一样,需要使用不同的线程来有效地交换数据。