Search code examples
javacollectionssynchronized

Understanding object ownership in Java


I'm reading Brian Goetz's Java Concurrency in Practice and have a question about the so-called object ownership concept. Here's what he stated:

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 is:

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

where SynchornizedCollection's constructor is:

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

So, if we call this method as follows:

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

we could modify the list's content later, so I'd say the synchronized wrappers have shared ownership.

What's wrong with that?


Solution

  • What's wrong with that?

    I'll quote the documentation from the Collections class:

    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.

    So the documentation tells you to NOT retain a reference to the original list and modify it. You have to go through the returned collection or it doesn't work.

    I don't think there's any way of enforcing ownership in Java programmatically. Auto-pointers can't exist (or at least they aren't implemented, so no APIs use them). You just have to read the docs and write correct code.