multithreading - Arraylist synchronization for add only call -
i have question regarding synchronizing array list. using araylist in multi threaded environment callable interface. pass arraylist object callable method kid threads add together entry arraylist. don't utilize arraylist iterate anywhere in kid thread classes. should need synchronize arraylist still if add together 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
yes, have synchronize inserts.
arraylist not synchronized, see
https://docs.oracle.com/javase/7/docs/api/java/util/arraylist.html
so if adding elements concurrently several threads must synchronize it, because modifying concurrently inner structure.
from javadoc:
note implementation not synchronized. if multiple threads access arraylist instance concurrently, , @ to the lowest degree 1 of threads modifies list structurally, must synchronized externally. (a structural modification operation adds or deletes 1 or more elements, or explicitly resizes backing array; simply setting value of element not structural modification.) typically accomplished synchronizing on object naturally encapsulates list. if no such object exists, list should "wrapped" using collections.synchronizedlist method. best done @ creation time, prevent accidental unsynchronized access list:
list list = collections.synchronizedlist(new arraylist(...));
multithreading arraylist synchronization
No comments:
Post a Comment