Brian Goetz (Mr Concurrency) has finished Java Concurrency in Practice a book in which he has sweat blood and tears for sure.
If you mention anything to him right now he will immediately be able to tell you about the concurrency issues and how we have multicores now, and hence we will soon be screwed.
Someone was complaining about list.getLast()
instead of list.get(list.size()-1)
Brian pointed out that this isn’t about ease of use, but that (of course):
list.getLast() would be atomic, whereas list.get(list.size()-1) would
not, and could throw NPE even for a nonempty list if a list element were
removed by another thread at just the wrong time.Um, I’ve got to stop doing that.
Congrats on JCiP Brian.
April 19th, 2006 at 9:07 pm
Yep, it’s been on order for a while now… hope it ships soon…
April 19th, 2006 at 9:09 pm
Yep, it’s been on order for a while now… hope it ships soon…
April 20th, 2006 at 2:54 am
But any unguarded operations on a Collection has potentially the same problem:
if (!list.isEmpty()) object = list.get(0);
So you need to guard any set multiple accesses to make them atomic. It is fairly trivial to create a ReadWriteList implementation that transparently handles a ReadWriteLock for you, then you can guard your writes transparently:
interface ReadWriteList extends ArrayList, ReadWriteLock {}
ReadWriteList list = new ReadWriteListWrapper(new ArrayList());
list.readLock().lock();
if (!list.isEmpty()) object = list.get(0);
list.readLock().unlock();
You need to maintain your own lock/unlock blocks though, and you can’t transparently lock down your iterators unfortunately.
April 20th, 2006 at 3:19 am
Oops, I obviously meant extends List…
April 20th, 2006 at 8:46 am
Most List implementation are not synchronized by default. So list.getLast() would be just as bad as list.get(list.size()-1).
Dealing with concurrency issues is more complicated than just adding a synchronized modifier to a method or using a synchronized block. Only a good design and well defined concurrency path will make an multithreading application well behaved.
April 26th, 2006 at 2:19 am
Do I miss anything? I cannot find list.getLast() at java.util.List interface
May 15th, 2006 at 5:41 am
Yim: It’s on LinkedList.
But, yes, why’s it not on List, as I tend to use the interface rather than the implementation for my references.
Also, why does LinkedHashSet not implement List too?