@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?

6 comments
Comment actions Permalink

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:

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?

>

---
Original message URL: http://www.jetbrains.net/devnet/message/5256383#5256383


--
Martin Fuhrer
Fuhrer Engineering AG
http://www.fuhrer.com

0
Comment actions Permalink

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.

0
Comment actions Permalink

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

0
Comment actions Permalink

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.

0
Comment actions Permalink

Yep. got it. Thanks

0

Please sign in to leave a comment.