Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Autocloseable support in GuardedByChecker #4207

Open
Edarke opened this issue Nov 30, 2023 · 0 comments
Open

Autocloseable support in GuardedByChecker #4207

Edarke opened this issue Nov 30, 2023 · 0 comments

Comments

@Edarke
Copy link

Edarke commented Nov 30, 2023

Currently, GuardedByChecker reports false positives if a lock is being held in a try-with-resources block. There's a TODO in the codebase for this, but I didn't see any tickets for this issue so I thought I'd start a discussion.

// TODO(cushon) - recognize common try-with-resources patterns. Currently there is no
// standard implementation of an AutoCloseable lock resource to detect.

When JDK 7 introduced the try-with-resources block, there was a lot of discussion about whether various locks should be supported. Eventually, it was decided that it would not be supported in the standard Java class library; however, the choice was controversial enough that I'm sure many people are using one of the many third party libraries to solve this or rolling their own Autoclosable solution. Would it be possible to add a heuristic to detect these AutoCloseable wrappers? Maybe by allowing users to explicitly annotate them?

Maybe something that looks like this?

class Example {

   private final Lock lock = new Lock();
  
   @GuardedBy("lock")
   private int counter;

   void test() {
      try (var u = LockUtil.lock(lock)) {
        ++counter;
      }
   }
}

class LockUtil {

   @MustBeClosed
   @LockHolder("delegate") // Informs HeldLockAnalyzer to add 'delegate' to heldset. Maybe even verify unlock is called by close?
   public static AutoCloseable lock(Lock delegate) {
      delegate.lock();
      return delegate::unlock;
   }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant