Java ReentrantReadWriteLocks - how to safely acquire write lock?

前端 未结 12 1761
小蘑菇
小蘑菇 2020-11-28 19:00

I am using in my code at the moment a ReentrantReadWriteLock to synchronize access over a tree-like structure. This structure is large, and read by many threads at once wit

12条回答
  •  广开言路
    2020-11-28 19:36

    I suppose the ReentrantLock is motivated by a recursive traversal of the tree:

    public void doSomething(Node node) {
      // Acquire reentrant lock
      ... // Do something, possibly acquire write lock
      for (Node child : node.childs) {
        doSomething(child);
      }
      // Release reentrant lock
    }
    

    Can't you refactor your code to move the lock handling outside of the recursion ?

    public void doSomething(Node node) {
      // Acquire NON-reentrant read lock
      recurseDoSomething(node);
      // Release NON-reentrant read lock
    }
    
    private void recurseDoSomething(Node node) {
      ... // Do something, possibly acquire write lock
      for (Node child : node.childs) {
        recurseDoSomething(child);
      }
    }
    

提交回复
热议问题