@Nullable class field
I write simple test case class:
public class A
{
@Nullable Integer b;
private void a() {
b.compareTo(1);
}
}
IDEA Inspector highlights that b.compareTo(1); may produce NPE. I used quick fix suggested by IDEA and rewrote class as:
public class A
{
@Nullable Integer b;
private void a() {
if (b != null) {
b.compareTo(1);
}
}
}
but IDEA Inspector still highlights that b.compareTo(1); may produce NPE.
Whats wrong? IDEA bug?
Please sign in to leave a comment.
The problem is that you are accessing the field b twice. And in a
multithreaded environment it is possible that another thread is changing
b to null just between those two calls. The only way to make this really
foolproof is to write something like this:
Integer x = b;
if (x != null) {
x.compareTo(1);
}
On 2/10/2010 2:46 PM, Den Orlov wrote:
>
>
>
>
>
>
>
>
--
Martin Fuhrer
Fuhrer Engineering AG
http://www.fuhrer.com
Martin is right of course, but I really would like to have some inspection annotation or such to mark a class instance as "single-threaded".
For example I have lots of Seam components that are scoped to a single http request, so no such multi-threading problems can happen.
Martin,
In you example Integer x is still shared between threads since it is just reference to shared b.
But inspector warning goes off. Seems that it is not correct behaviour.
Den
http://jetbrains.dzone.com/tips/concurrency-hot-try-jcip
You're right, it is possible that several threads access the Integer object simultaneously. But that's no problem, as an Integer object is immutable. The only thing which can happen is that another thread is assigning another Integer object to field b, but it is impossible to alter the one which is referenced by the local variable x. So IDEA is perfectly right in not highlighting this usage pattern.
Yep. got it. Thanks