为什么使用 Final 作为修饰符时此缓存不起作用
我有这段代码来获取此实例的 Cursor 一次,日志显示它被调用了很多次,尽管我标记为最终的。我缺少什么?
private Cursor getAllContactsCached() {
final Cursor c=this.getList();
return c;
}
getAllContactsCached 方法应该检索列表一次,第二次应该重用最终对象来返回
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Java 在函数中没有静态局部变量(像 C 那样);
final
意味着与你正在做的事情完全不同的事情。获得这种静态的唯一方法是使用实例或类成员,例如:(
这是特定于实例的方式;您也可以以类范围的方式执行此操作,但我猜这不是适用于
Cursor
。)请注意,整个方法是同步的。如果您只有一个游标实例是至关重要的,那么这一点就很重要。如果这只是一种优化,而不是至关重要的,那么您可以忍受竞争条件而不进行同步,在这种情况下,您最终可能会得到该函数返回的两个不同的游标。 (您可能会想使用双重检查锁定习惯用法,但事实并非如此。除非您使用
volatile
变量,否则无法使用 Java,并且它 最终会更好继续进行同步。)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.:
(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.)没有。
final
表示您承诺不更改它。如果您希望它不改变,您需要将其设置为静态或类成员。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.