Publishing Non-Thread Safe Object Fields in a Thread-Safe Manner

前端 未结 1 720
半阙折子戏
半阙折子戏 2021-02-15 11:47

I\'ve got a problem with Java concurrency. Yes, I looked at questions with almost the exact same title, but they all seemed to be asking subtly different things. Yes, I\'ve read

1条回答
  •  盖世英雄少女心
    2021-02-15 12:14

    If reference to unsafe objects has escaped to surrounding threads - you can not do anything to stop other threads to mutate the state, so you should keep the references safe. Make the data private, throw in methods that encapsulate access and modification and make thread-safe copies (yes, cloning is cumbersome) if you ever need to return complex objects.

    Try to look at http://en.wikipedia.org/wiki/Law_of_Demeter design principle. quote: In particular, an object should avoid invoking methods of a member object returned by another method. For many modern object oriented languages that use a dot as field identifier, the law can be stated simply as "use only one dot". That is, the code a.b.Method() breaks the law where a.Method() does not. As a simple example, when one wants to walk a dog, it would be folly to command the dog's legs to walk directly; instead one commands the dog and lets it take care of its own legs.

    ps: I'm afraid it is open-ended question.

    0 讨论(0)
提交回复
热议问题