As part of my design, I have a singleton DataSchema class whose role is to store the fixed schema information as read from the database file header. The class provides methods to provide such things as the name of field-number-n etc, which it does by looking up the information in an ArrayList.
One such method is:
I'm sudenly unsure whether databaseColumns.get(n) is thread safe. Might the get method on the List leave the List in an unspecified state if a second thread slices-in halfway through? Should I be synchronizing the method even though I'm not updating the List?
You don't have to synchronize this get method. I didn't and I didn't lose marks for it. It is possible that a second thread enters the method and changes the value of n before the first thread calls databaseColumns.get(n); However, I personally don't think the marker will look for this.
If you want to be safe, perhaps you can try Collections.synchronizedList(List), which returns a thread-safe List based on the argument List.
I agree with Kang. Also, probably your collection is intialized once at start-up and never changed after that, so then concurrency is not an issue at all.
If you want to be safe use a synchronized list or a Vector, which is essentially a thread-safe ArrayList (which is why you should always use an ArrayList when you don't need thread-safety).
SCJP 1.4, SCJD
Joined: Mar 20, 2005
Thanks for the reassurance. Frans - you're right, the List is initialized once at start up and not altered after that. Sorry, I forgot to ask - are iterators over the list thread safe? That is - if two threads each independently obtain an iterator over the List and read from it, can the iterators interfere with each other?