Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Synchronized Collections

 
Neil Renaud
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Right, I've got a

Now this is sort of thread safe. However if I want to check an index is in the list and then retrieve it I wold normally do code like this



Now calling this isn't thread safe. So i'd have to put a sychronize block around it. However I thought of another horrible solution...



How offensive do people think that is? I think i'm going to avoid doing it but I wanted to see what people thought.

Neil
 
Daniel Dalton
Ranch Hand
Posts: 146
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No, I think it would be a bad idea to do that. If you take a look at the book "Effective Java" by Joshua Bloch which is part of the Java Series from Sun, something similar to this idiom is described in item 39 on exception handling.

They say, and I quote:

  • Because exceptions are designed to be used under exceptional circumstances, few if any JVM implementations attempt to optimize their performance. It is generally expensive to create, throw, and catch an exception.
  • Placing code inside a try-catch block precludes certain optimizations that modern JVM implementations might otherwise perform.


  • It's not as though IndexOutOfBounds is that unexpected really, so I guess
    if you can do it a different way it would be better.
     
    Frans Janssen
    Ranch Hand
    Posts: 357
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Putting everything inside a synchronized block has its own performance penalty and personally I feel that performance in this assignment should be less important than clear and maintainable code.

    I agree with Daniel's statement though that exceptions should be reserved for exceptional situations. So I would make the following considerations:

  • If supplying an out-of-range index is something that can happen regularly, e.g. because a client cannot know how many records there are, I would prefer the first solution (inside a synchronized block);
  • If clients should be able to know what records exist and supplying an out-of-range index can only happen for malfunctioning or otherwise "stupid" clients, then I think the second solution is very acceptable.

  • Frans.
     
    • Post Reply
    • Bookmark Topic Watch Topic
    • New Topic