GuardedBy false positive with Runnable passed to a user method known to invoke synchronously
- Dominant language
- Java
- Stars
- 7.2k
- Forks
- 820
- Avg merge
- 5h 9m
- Merged PRs (30d)
- 50
Description
The `@GuardedBy` annotation has a false positive when we pass a lambda or method reference that accesses guarded items, even if we know it is invoked immediately synchronously.
Consider the following case:
```java
class Transaction {
@GuardedBy("this")
int x;
public synchronized void handle() {
doSomething(() -> {
x++; // compilation error, requires extraneous synchronized block to satisfy the checker
});
}
private void doSomething(Runnable r) {
r.run();
}
}
```
The above code fails to compile without adding a `synchronized` block inside the lambda. This grows cumbersome in codebases where this pattern is common, for example, a `safeRun` method that wraps a `Runnable` with error handling and logging.
I suggest we add a parameter annotation `@RunsImmediately` to indicate the call is safe without the extraneous synchronization block. There already exists a [whitelist for common built-in Java functions](https://github.com/google/error-prone/blob/be8896aee16f3de5f95d188f3ba1045e36e872ac/core/src/main/java/com/google/errorprone/bugpatterns/threadsafety/HeldLockAnalyzer.java#L68-L89), so this would allow people to whitelist their own methods.
Contributor guide
Research direction
Start with HeldLockAnalyzer.java and its existing whitelist for common built-in Java functions, then trace how @GuardedBy analyzes lambdas and method references passed to Runnable parameters. Add support for the proposed @RunsImmediately parameter annotation so known synchronous calls do not require an extraneous synchronized block, and verify the example case is accepted.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- java
- Domain
- compilers, devtools
- Issue type
- Feature
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Quiet
- Clarity
- Mostly clear
- Newbie friendliness
- 55/100