-2

Is there any possibility to synchronize an ArrayList?

I have multiple threads and they have access to an ArrayList. So if I put with thread A an Element into my List is there any chance that at the same time the List of thread B gets filled with the same Element and the same story with thread B towards thread A.

I tried Synchronized List but it does not work.

Brandon Minnick
  • 13,342
  • 15
  • 65
  • 123
GermanNab
  • 43
  • 6
  • 1
    *I tried Synchronized List but it does not works.* Can you elaborate on this attempt? Preferably with code? – Joe C Jan 06 '18 at 15:42
  • i have a main class with a main methode. my issue is, if i initialize a List myElements in my main method and take it as an argument for my Manipulate class (as constructor argument). after manipulating im printing in my main class the size of myElements it is still zero. CopyOnWriteArrayList myElements= new CopyOnWriteArrayList(); How can i get the update in the main method, how can i see the manipulated list also in my main class in my main Method? – GermanNab Jan 06 '18 at 16:47
  • @GermanNab Could you please provide your sample code – Ramesh Papaganti Jan 06 '18 at 17:54
  • ah sorry guys. im fairly new here. i will close this i dont want to waste your time. – GermanNab Jan 06 '18 at 18:57

1 Answers1

0

Collections api available for synchronizedList

synchronizedList
public static <T> List<T> synchronizedList(List<T> list)
Returns a synchronized (thread-safe) list backed by the specified list. In order to guarantee serial access, it is critical that all access to the backing list is accomplished through the returned list.
It is imperative that the user manually synchronize on the returned list when iterating over it:

  List list = Collections.synchronizedList(new ArrayList());
      ...
  synchronized (list) {
      Iterator i = list.iterator(); // Must be in synchronized block
      while (i.hasNext())
          foo(i.next());
  }

Failure to follow this advice may result in non-deterministic behavior.
The returned list will be serializable if the specified list is serializable.

Parameters:
list - the list to be "wrapped" in a synchronized list.
Returns:
a synchronized view of the specified list.
gati sahu
  • 2,576
  • 2
  • 10
  • 16
  • You could at least link to the Javadoc if you just copy & paste it here, without even formatting it properly. – Robert Jan 06 '18 at 18:54