I need to synchronize both the method and the object

So, I have the following list accessed from multiple threads:

ArrayList<String> listOfString = Collections.synchronizedList(new ArrayList<String>());

I know that when I iterate over a list, I have to synchronize like this:

 synchronized(listOfString) { for(String s : listOfString) System.out.println(s); listOfString.clear(); } 

And what if I want to delete something, I do this:

 public void removeString(String s) { listOfString.remove(s); } 

or that:

 public synchronized void removeString(String s) { listOfString.remove(s); } 
+4
source share
1 answer

As you said, the list is already synchronized, so your removeString method removeString not be synchronized either.

Note that if one of your methods contains a non-atomic operation (let's say you want to check if your list contains something and then change the list accordingly), you may need to add another level of synchronization.

Finally, you did not seem to notice that this method:

 public synchronized void removeString(String s) 

synchronizes with another lock (it synchronizes to this ). So, back to the example above, you would write it down:

 public void someMethod() { synchronized(listOfString) { //use the same lock! if(listOfString.size() == 123) { listOfString.add("lucky day"); } } } 
+7
source

Source: https://habr.com/ru/post/1481408/


All Articles