How to synchronize file access in a Java servlet?

老子叫甜甜 提交于 2019-11-29 04:49:25

I guess that using the synchronized(){} keyword would also not work since I want to synchronize file system access and not access to variables/objects.

Using synchronized can work. You are assuming that if you want to control access to object X from multiple threads, you must use synchronized on that object. You don't. You can use synchronized on any object, provided all the accesses use the same object.

In fact, it is often better to use a separate private lock object for synchronization, because it is then impossible for code outside the class to synchronize on the lock.

So , you might have something like this, with one instance for each shared file:

 public class SharedFile
 {
      private final File path;
      private final Object lock = new Object();

      public SharedFile(File path) {
         this.path = path;
      }

      public void process(.....) throws IOException {
         synchronized(lock) {
            try(InputStream = new FileInputStream(path)) {
               ....
            }
         }
      }
 }

You can use a Semaphore, as follows:

private static Semaphore semaphore = new Semaphore(1);

public void doSomeChangesTo(JSONObject json) {
    try {
        semaphore.acquire();

        // doSomeChangesTo

    } finally {
        semaphore.release();
    }
}

You should use a Semaphore to protect access to the resource. (Your file.) See http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Semaphore.html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!