确保在访问成员变量之前完成初始化方法

编程入门 行业动态 更新时间:2024-10-26 04:26:46
本文介绍了确保在访问成员变量之前完成初始化方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

是否有一种方法可以确保通过一个线程在 volatile static 成员变量上运行的一组方法能够完成并在其他线程之前完成访问此成员变量?我正在尝试类似的方法,但是我不确定是否可以使用.

Is there a way of ensure that a set of methods operating on a volatile static member variable via one thread will be done and over with before other threads access this member variable? I am trying something like this, but I am not sure if it would work.

public class MyClass { private static final Object lock = new Object(); public static volatile MyObj mo; //assume null will be checked before access public static void initialize() { if (mo == null) { synchronized(lock) { mo = new MyObj(); mo.doInit(); mo.doMoreInit(); } } } }

推荐答案

您需要将mo的赋值延迟到之后被调用所有方法(即,使用局部变量然后赋值) mo作为最后步骤).

You need to delay the assignment of mo until after all the methods are called (i.e. use a local variable and then assign mo as the last step).

请注意,您实际上是在实施双重检查锁定(尽管使用volatile使其可以正确"工作).您需要在同步块中的 中再次检查mo是否为空.

Note, you are essentially implementing double checked locking (although using volatile makes it work "correctly"). you need to check mo for null again within the synchronized block.

此外,还有其他一些(更好一些)的模式,例如使用类初始化模式来管理同步. en.wikipedia/wiki/Singleton_pattern

also, there are some other (somewhat better) patterns for this like using the class initialization pattern for managing the synchronization. Pretty much every pattern imaginable is detailed here en.wikipedia/wiki/Singleton_pattern

更多推荐

确保在访问成员变量之前完成初始化方法

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

发布评论

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

>www.elefans.com

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