不可变对象和延迟初始化.

编程入门 行业动态 更新时间:2024-10-09 04:26:08
本文介绍了不可变对象和延迟初始化.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

www.javapractices/topic/TopicAction.do?Id = 29

以上是我正在查看的文章.不可变的对象极大地简化了您的程序,因为它们:

Above is the article which i am looking at. Immutable objects greatly simplify your program, since they:

允许hashCode使用延迟初始化并缓存其返回值

  • 有人可以向我解释作者在上述内容上要说的内容吗?线.
  • 如果我的课程标记为final及其实例变量,是否为我的课程 immutable 仍然不是final,并且 vice-versa 我的实例变量是final ,而 class是正常.
  • Can anyone explain me what the author is trying to say on the above line.
  • Is my class immutable if its marked final and its instance variable still not final and vice-versa my instance variables being final and class being normal.
推荐答案

正如其他人所解释的,由于对象的状态不会改变,因此哈希码只能计算一次.

As explained by others, because the state of the object won't change the hashcode can be calculated only once.

简单的解决方案是在构造函数中对其进行预先计算,并将结果放置在最终变量中(这可以确保线程安全).

The easy solution is to precalculate it in the constructor and place the result in a final variable (which guarantees thread safety).

如果您希望进行惰性计算(仅在需要时才计算哈希码),但要保留不可变对象的线程安全性,就比较棘手.

If you want to have a lazy calculation (hashcode only calculated if needed) it is a little more tricky if you want to keep the thread safety characteristics of your immutable objects.

最简单的方法是声明一个 private volatile int hash; ,如果它为0,则运行计算.除了其哈希码实际上为0的对象(如果您的40亿个中的1亿个对象,则将获得延迟)哈希方法分布均匀).

The simplest way is to declare a private volatile int hash; and run the calculation if it is 0. You will get laziness except for objects whose hashcode really is 0 (1 in 4 billion if your hash method is well distributed).

或者,您可以将其与易失性布尔值结合使用,但需要注意两个变量的更新顺序.

Alternatively you could couple it with a volatile boolean but need to be careful about the order in which you update the two variables.

最后,为了提高性能,可以使用String类使用的方法,该方法使用额外的局部变量进行计算,从而可以在确保正确性的同时摆脱volatile关键字.如果您不完全理解为什么这样做的话,这最后一种方法很容易出错...

Finally for extra performance, you can use the methodology used by the String class which uses an extra local variable for the calculation, allowing to get rid of the volatile keyword while guaranteeing correctness. This last method is error prone if you don't fully understand why it is done the way it is done...

更多推荐

不可变对象和延迟初始化.

本文发布于:2023-11-12 01:58:03,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1580187.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:初始化   对象

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!