Re: Is the @ThreadSafe annotation from JCIP incompatible with callbacks?
neuneudr@yahoo.fr wrote:
if you want every method of a class to be synchronized, you
can use the @ThreadSafe annotation from JCIP and then use
FindBugs to find violations (at least that's the theory ;)
Making every method of a class synchronized doesn't necessarily make the class
thread safe.
You don't need the annotation to make every method synchronized.
However I'm wondering, when you have callbacks, those callbacks
are basically alien method calls and hence you cannot synchronize
every method?
Do you mean callbacks that the synchronized class calls, or callbacks that the
class donates to other class instances to call?
So the following is incorrect because there's an alien method call:
public void synchronized doSomeStuff() {
...
if ( statechanged ) {
notifyObservers(); // alien method call
}
}
There's not enough information here to determine if the method is correct, or
even what "correct" means for this class.
I have to write:
public void doSomeStuff() {
synchronized(this) {
...
}
if ( statechanged ) {
notifyObservers();
}
}
And then it means as soon as I've got callback I cannot
use the @ThreadSafe annotations from JCIP?
That does not follow.
Thread safety is what the class guarantees (or fails to) about its own state.
It certainly is possible to make a class thread safe and have it call
callback methods.
I haven't used the '@ThreadSafe' annotation, but based on my reading of /Java
Concurrency in Practice/ it should be fine to mark the class thread safe if it
is, indeed, thread safe.
To move expensive code blocks out of the critical section is good practice
regardless.
--
Lew