• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Arraylist synchromization for add method

 
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi All,

I have a question regarding synchronizing Array List. I am using an ArayList in a multi threaded environment with Callable interface. I pass an Arraylist object to the Callable method where all the child threads add an entry into the arraylist.
I don't use the arraylist to Iterate anywhere in the Child thread classes. Should I need to synchronize the Arraylist still even if I do only add into that?

Snippet below, please help

main Class
...
ArrayList<String> arrList = new ArrayList<String>();
ImplCallable implCallable = new ImplCallable (arrList);
.
.
.
ImplCallable Class

ImplCallable (ArrayList<String> arrList)
{
this.arrList = arrList;
}
call()
{
.
.
.
.
synchronized(arrList )
{
arrList.add(addString);
}

}

Regards
Subash
 
author
Posts: 23956
142
jQuery Eclipse IDE Firefox Browser VI Editor C++ Chrome Java Linux Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Subash Murugan wrote:Should I need to synchronize the Arraylist still even if I do only add into that?



The ArrayList class is not thread safe, so a thread definitely need to synchronize if it is doing anything that is modifying the structure of the class. Also, if a thread is only reading (not modifying) the class, but another thread is modifying the structure of the class, then it too, needs to synchronized.

This, of course, applies to any non thread safe data structure -- and not just the ArrayList class.

Henry
 
Ranch Hand
Posts: 162
1
Android Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Adding to ArrayList is not an Atomic Operation. It is divided into various small operations like as follows

1. Read the last index
2. Add 1 to this index
3. Replace the last index value with the new value


So if 2 threads got interleaved in these steps , then there might be synchronization issues.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic