同步集合包装工厂方法如何“拥有"?对象传递进去了吗? [英] How does a Synchronized Collection Wrapper factory method "own" the object passed into it?

查看:52
本文介绍了同步集合包装工厂方法如何“拥有"?对象传递进去了吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在《 Java Concurrency in Practice》一书中,Brian Goetz说,传递给类的构造函数和方法的对象不归类所有.是因为他们来自外面,而班级却无法控制他们吗?

In the book Java Concurrency in Practice , Brian Goetz says that objects passed to constructors and methods of a class are not owned by the Class itself . Is it because they are coming from outside and the class has no control over them ?

他继续说,如果显式设计了一种方法来转移传入的对象的所有权(例如,同步集合包装器工厂方法),则这是一个例外.有人可以举一个例子,并向我解释如何将其视为例外吗?

He goes on to say that there is an exception to this in cases where a method is explicitly designed to transfer ownership of objects passed in (such as Synchronized collection wrapper factory methods). Can some one give an example of the same and explain to me how this can be considered as an exception ?

推荐答案

例外是

List<String> syncList = Collections.synchronizedList(new ArrayList<>());

您可以看到,只要包装对象拥有对基础数组列表的唯一可访问引用,synchronizedList的设计方式将承担线程安全责任的所有权.

You can see that the way synchronizedList is designed it assumes ownership of thread safety responsibility so long as the wrapper object holds the only reachable reference to the underlying array list.

这篇关于同步集合包装工厂方法如何“拥有"?对象传递进去了吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆