wyona / yanel

http://www.yanel.org
Apache License 2.0
10 stars 5 forks source link

Synchronize save and read Properties of VirtualFileSystemNode #48

Open michaelwechner opened 11 years ago

michaelwechner commented 11 years ago

The class

src/impl/java/org/wyona/yarep/impl/repo/vfs/VirtualFileSystemNode.java

has the methods

readProperties()

and

saveProperties()

which should be synchronized, because otherwise it can happen that while one process/thread is writing, the other process/thread is already reading, and hence gets only half of the data.

baszero commented 8 years ago

Remains the question of how to synchronize. Synchronizing whole methods is known to be slow. Much faster is using the java.util.concurrent.locks.ReentrantReadWriteLock.

Example:

in the class you add

    private static final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock(Boolean.TRUE); // true = fair policy, order of lock acquisition is preserved
    private static final Lock r = rwl.readLock();
    private static final Lock w = rwl.writeLock();

and then in all code sections requiring WRITE access:

private static void exampleUpdate() {
  w.lock(); // this thread waits until all preceding read threads have finished
  try {
    // DO THE WRITE STUFF HERE, as short as possible!
  } finally {
    w.unlock();
  }
}

and in all code sections requiring READ access:

private static void exampleGetData() {
  r.lock(); // this thread waits until all preceding read threads have finished
  try {
    // just READ 
  } finally {
    r.unlock();
  }
}

This way you have a very isolidated synchronization point and you don't have to care about threading issues in the JVM (like using volatile on locking objects etc.)