Java: Is volatile / final required for reference to synchronized object?

后端 未结 5 779
陌清茗
陌清茗 2021-01-04 02:52

This seems a pretty basic issue, but I cannot find a clear confirmation.

Let\'s say I have a class properly synchronized in itself:

public class Sync         


        
5条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-04 03:20

    If I need to have a refence to an instance of that class, shared between threads, I do still need to declare that instance volatile or final, am I right?

    Yes, you are right. In this case you have two shared variables:

    private int field

    private SyncClass mySharedObject

    Because of the way you have defined SyncClass any reference to a SyncClass will give you the most up to date value of that SyncClass.

    If you don't synchronize the access to mySharedObject correctly (a non-final, non-volatile) field and you change the value of mySharedObject you may get a mySharedObject which is out of date.

提交回复
热议问题