Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Arraylist synchromization for add method  RSS feed

 
Subash Murugan
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • 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
 
Henry Wong
author
Sheriff
Posts: 23283
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • 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
 
Sangel Kapoor
Ranch Hand
Posts: 162
1
Android Java
  • Mark post as helpful
  • send pies
  • 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.
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!