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

烂漫一生 提交于 2019-12-03 13:39:34

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!