File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Do I need to synchronize read-access to a shared List object

 
Daniel Dalton
Ranch Hand
Posts: 146
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?

Any assistance much appreciated.
 
Kang Wang
Greenhorn
Posts: 12
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Daniel,

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.

Hope this helps.

Kang Wang
SCJP, SCWCD, SCJD
 
Frans Janssen
Ranch Hand
Posts: 357
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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).

Frans.
 
Daniel Dalton
Ranch Hand
Posts: 146
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Neil Renaud
Greenhorn
Posts: 15
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think you should look up ConcurrentModificationException and under what conditions it is thrown by an iterator.

You are probably ok if you aren't going to edit anything. That being said if you aren't editing anything you can use Collections.unmodifiableList(yourList)

HTH
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic