Forums Register Login

Synchronized Collections

+Pie Number of slices to send: Send
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
+Pie Number of slices to send: Send
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.
    +Pie Number of slices to send: Send
    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.
    What are you doing in my house? Get 'em tiny ad!
    a bit of art, as a gift, the permaculture playing cards
    https://gardener-gift.com


    reply
    reply
    This thread has been viewed 624 times.
    Similar Threads
    RecordNotFoundException
    Failed b/c of locking. Any ideas?
    lock(int recNo) throws RecordNotFoundException
    Help with Arrays and ArrayLists
    Making the Data Class a Singleton & Thread Safe
    More...

    All times above are in ranch (not your local) time.
    The current ranch time is
    Mar 28, 2024 10:31:59.