问题
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 ?
回答1:
An exception is
List<String> syncList = Collections.synchronizedList(new ArrayList<>());
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.
回答2:
Owning in this sense generally relates to who has the responsibility for cleaning up any resources acquired by the object, ie calling Close
, Dispose
or other such methods.
If a method returns an object for use (such as a factory method) then it makes no sense for this object to be closed before being returned, since it would then become unuseable - thus ownership is transferred and it becomes the responsibility of the calling code to clean up.
In certain cases it makes sense to transfer ownership to called code. It is often the case when the usage of the new object is agnostic of it's underlying mechanisms. For example, if I had an interface for a class capable of reading a string, I would not expect to use the implementations in different ways depending on where the string was read from (file stream, network stream, in memory, etc). Hence if the implementation required an instance of a Stream, it would be sensible for ownership of the Stream to pass to the string reader implementation rather than the class that created the Stream.
来源:https://stackoverflow.com/questions/11341281/how-does-a-synchronized-collection-wrapper-factory-method-own-the-object-passe