allow to omit lock when reading volatile field in "Unguarded field access" inspection

This commit is contained in:
Bas Leijdekkers
2017-02-03 16:18:57 +01:00
parent 28e45f78c3
commit 595fef1b17
3 changed files with 24 additions and 3 deletions
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2016 JetBrains s.r.o.
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -54,7 +54,6 @@ public class FieldAccessNotGuardedInspection extends BaseJavaBatchLocalInspectio
return new Visitor(holder);
}
private static class Visitor extends JavaElementVisitor {
private final ProblemsHolder myHolder;
@@ -83,6 +82,10 @@ public class FieldAccessNotGuardedInspection extends BaseJavaBatchLocalInspectio
} catch (IncorrectOperationException ignore) {
return;
}
if (guardExpression instanceof PsiThisExpression && !PsiUtil.isAccessedForWriting(expression) &&
field.hasModifierProperty(PsiModifier.VOLATILE)) {
return;
}
final PsiMethod containingMethod = PsiTreeUtil.getParentOfType(expression, PsiMethod.class);
if (containingMethod != null) {
if (JCiPUtil.isGuardedBy(containingMethod, guard) || containingMethod.isConstructor()) {
@@ -0,0 +1,13 @@
import javax.annotation.concurrent.GuardedBy;
class CheapReadWriteLock {
// Employs the cheap read-write lock trick
// All mutative operations MUST be done with the 'this' lock held
@GuardedBy("this") private volatile int value;
public int getValue() { return value; }
public synchronized int increment() {
return value++;
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2013 JetBrains s.r.o.
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -42,6 +42,11 @@ public class FieldAccessedNotGuardedInspectionTest extends LightCodeInsightFixtu
doTest();
}
public void testCheapReadWriteLock() {
myFixture.addClass("package javax.annotation.concurrent;\n" + getGuardedByAnnotationText());
doTest();
}
private void doTest() {
myFixture.testHighlighting(true, false, false, getTestName(true) + ".java");
}