IDEA-111282 (False positive on "while loop spins on field", where wait() is used)

This commit is contained in:
Bas Leijdekkers
2015-05-11 11:10:30 +02:00
parent ec807588db
commit 6d2e193373
2 changed files with 32 additions and 2 deletions
@@ -1,5 +1,5 @@
/*
* Copyright 2003-2012 Dave Griffith, Bas Leijdekkers
* Copyright 2003-2015 Dave Griffith, Bas Leijdekkers
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -74,12 +74,28 @@ public class WhileLoopSpinsOnFieldInspection extends BaseInspection {
if (field == null) {
return;
}
if (body != null && VariableAccessUtils.variableIsAssigned(field, body)) {
if (body != null && (VariableAccessUtils.variableIsAssigned(field, body) ||
containsWaitCall(body))) {
return;
}
registerStatementError(statement);
}
private boolean containsWaitCall(PsiElement element) {
final boolean[] result = new boolean[1];
element.accept(new JavaRecursiveElementWalkingVisitor() {
@Override
public void visitMethodCallExpression(PsiMethodCallExpression expression) {
super.visitMethodCallExpression(expression);
if (ThreadingUtils.isWaitCall(expression)) {
result[0] = true;
stopWalking();
}
}
});
return result[0];
}
@Nullable
private PsiField getFieldIfSimpleFieldComparison(PsiExpression condition) {
condition = PsiUtil.deparenthesizeExpression(condition);
@@ -69,4 +69,18 @@ class WhileLoopSpinsOnField2
}
}
}
class WhileLoopSpinsOnFieldFalsePosDemo {
private boolean field = false;
public synchronized void setAndNotify() {
field = true;
this.notifyAll();
}
public synchronized void waitForStuff() throws InterruptedException {
// IDEA incorrectly reports "'while' loop spins on field" here:
while (!field) { // <— this line
this.wait(); // this has the effect of synchronizing the field correctly
}
}
}