了解 Java 中的对象所有权

Understanding object ownership in Java

我正在阅读 Brian Goetz 的 Java 并发实践 并且对所谓的对象所有权概念有疑问。他是这样说的:

A class usually does not own the objects passed to its methods or constructors, unless the method is designed to explicitly transfer ownership of objects passed in (such as the synchronized collection wrapper factory methods).

Collections.synchronizedCollection(Collection) source 是:

public static <T> Collection<T> More ...synchronizedCollection(Collection<T> c) {
    return new SynchronizedCollection<T>(c);
}

其中 SynchornizedCollection 的构造函数是:

SynchronizedCollection(Collection<E> c) {
    if (c==null)
        throw new NullPointerException();
    this.c = c;
    mutex = this;
}

所以,如果我们调用这个方法如下:

List<Date> lst;
//initialize the list
Collection<Date> synchedLst = Collections.syncrhonizedCollection(lst);
//modify lst's content

我们可以稍后修改列表的内容,所以我想说同步包装器具有共享所有权。

这有什么问题吗?

What's wrong with that?

您没有阅读文档。

https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#synchronizedCollection-java.util.Collection-

Returns a synchronized (thread-safe) collection backed by the specified collection. In order to guarantee serial access, it is critical that all access to the backing collection is accomplished through the returned collection.

因此文档告诉您不要保留对原始列表的引用并对其进行修改。您必须通过返回的集合,否则它不起作用。

我认为没有任何方法可以通过编程方式在 Java 中强制执行所有权。 Auto-pointers 不存在(或者至少它们没有实现,所以没有 API 使用它们)。你只需要阅读文档并编写正确的代码。