Reputation: 6440
I have a method which should thread-safely do some processing over multiple fields of the class. This method is called in multiple loops, thus I don't lock any mutexes inside it, but require a caller to lock them, using a @GuardedBy
annotation, something like this:
@GuardedBy("this")
void foo(int x) {
mField1 = x + mField2;
mField2 = x;
}
But to make my class faster I introduce a fine-grained locking. mField1
and mField2
sometimes are updated simultaneously, but sometimes are not, thus I introduce separate locks for them. How do I represent this logic in the annotation?
I tried coding something like
@GuardedBy("mField1Lock")
@GuardedBy("mField2Lock")
void foo(int x) {
mField1 = x + mField2;
mField2 = x;
}
But it does not compile: error: GuardedBy is not a repeatable annotation type
.
Upvotes: 0
Views: 615
Reputation: 8137
The @GuardedBy
annotation defined by JCIP (Java Concurrency In Practice) does not permit multiple mutexes.
Another problem is that JCIP provides no tool to check the annotations, but only uses them as documentation.
The Checker Framework solves both of these problems. Its @GuardedBy
annotation permits multiple mutexes, and its Lock Checker verifies the annotations, warning you about anywhere that your code might suffer a race condition due to failure to acquire a lock.
Upvotes: 1