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
Java doesn’t have static local variables in functions (like C has);
finalmeans 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.:
(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
volatilevariable, and it ends up just being better to go ahead and synchronize.)