views:

35

answers:

2

I have this code to get the Cursor once for this instance, and the Log shows it is called many times although I marked as final. What I am missing?

 private Cursor getAllContactsCached() {
        final Cursor c=this.getList();
        return c;
    }

getAllContactsCached method should retrieve list once, and the 2nd time it should reuse the final object for return

A: 

Nope. final means you promise not to change it. If you want it not to change you need to either make it static or a class member.

Thomas Jones-Low
-1 - "final means you promise not to change it" - Wrong. It means that you cannot change it. The problem here is that the OP is not understanding the scope/lifetime of `c`.
Stephen C
+4  A: 

Java doesn't have static local variables in functions (like C has); final means something completely different to what you're doing.

The only way you can get that kind of static is to use an instance or class member, e.g.:

class Foo {
    private Cursor theCursor;

    private synchronized Cursor getAllContactsCached() {
        if (this.theCursor == null) {
            this.theCursor = this.getList();
        }
        return this.theCursor;
    }
}

(That's the instance-specific way; you can also do this in a class-wide way, but I'm guessing that isn't appropriate for a Cursor.)

Note that the entire method is synchronized. This is important if it's crucial that you only ever have a single instance of the cursor. If it's merely an optimization, and not crucial, you could live with the race condition and not synchronize, in which case you could end up with two different cursors returned by the function. (You might be tempted to use the double-checked locking idiom, but it doesn't work with Java unless you use a volatile variable, and it ends up just being better to go ahead and synchronize.)

T.J. Crowder