Question

This code is from the book Effective Java

Object[] snapshot = list.toArray();// Locks list internally

I am mainly interested in the comment here . Does it make the list unmodifiable ? What does it mean to say that a list is locked internally ? How long is this lock kept ? Is there a better alternative to convert a List to an array ?

Was it helpful?

Solution

I would imagine that it means the list doesn't maintain a reference to the returned array, meaning that the array can be modified without affecting the original list from where it came. Likewise, any modifications to the list won't be reflected in the array.

This is important in terms of thread safety, because it means you can iterate on the contents of the list from a thread-safe perspective, without worrying about another thread altering the sttae of the list in the meantime. In this sense the state of the list is "locked" in the returned array, no matter what changes are made to the list afterwards - you can see it as taking a snapshot.

toArray(); doesn't alter the state of the list - so it doesn't make it unmodifiable or anything like that.

OTHER TIPS

Like the others said, I think that is about concurrency:

Text from javadoc of java.uitl.List

The returned array will be "safe" in that no references to it are maintained by this list. (In other words, this method must allocate a new array even if this list is backed by an array). The caller is thus free to modify the returned array.

Its about thread safety - i.e. conversion of the list to Array will be thread safe

Edit:
In simplest way - you can take it as

  • when Thread one is converting List -> Array no other thread is allowed to alter the list till the time Thread one has not completed the conversion

For those wondering where the "internal locking" takes place:

Please note that J. Bloch writes as an introduction for the given code: "For example, suppose you have a synchronized list (of the sort returned by Collections.synchroniedList) (...)"

In that case toArray() really "locks internal" because the implementation of the synchronized list will do just that (with a mutex) preventing any modification by other threads while the decoupled array is created.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top