Rails Recipes: Stuff you need Consultants, Startups, Students, and Rails
Apr 19

Concurrency and list.getLast()

Java, Tech Add comments

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.

7 Responses to “Concurrency and list.getLast()”

  1. Jason Carreira Says:

    Yep, it’s been on order for a while now… hope it ships soon…

  2. Jason Carreira Says:

    Yep, it’s been on order for a while now… hope it ships soon…

  3. Jed Wesley-Smith Says:

    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.

  4. Jed Wesley-Smith Says:

    Oops, I obviously meant extends List…

  5. Emmanuel Pirsch Says:

    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.

  6. Carfield Yim Says:

    Do I miss anything? I cannot find list.getLast() at java.util.List interface

  7. David Roussel Says:

    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?

Leave a Reply

Spam is a pain, I am sorry to have to do this to you, but can you answer the question below?

Q: What is the number before 3? (just put in the digit)