Object synchronization in Java

I am looking for something similar to this syntax, even if it does not exist.

I want to have a method action in the collection and for the lifetime of the method so that the collection is not confused.

So it might look like this:

private void synchronized(collectionX) doSomethingWithCollectionX() { // do something with collection x here, method acquires and releases lock on // collectionX automatically before and after the method is called } 

but instead, I'm afraid the only way to do this would be:

 private void doSomethingWithTheCollectionX(List<?> collectionX) { synchronized(collectionX) { // do something with collection x here } } 

Is this the best way to do this?

+6
source share
2 answers

Yes, that's just it .

 private synchronized myMethod() { // do work } 

is equivalent to:

 private myMethod() { synchronized(this) { // do work } } 

So, if you want to synchronize a different instance than this , you have no choice but to declare a synchronized block inside the method.

+4
source

In this case, it would be better to use a synchronized list:

 List<X> list = Collections.synchronizedList(new ArrayList<X>()); 

The collection API provides synchronized wrapper collections for thread safety.

Synchronization in the list in the body of the method blocks other threads that need to access the list for the entire life cycle of the method.

The alternative is manually synchronized with every access to the list:

 private void doSomethingWithTheCollectionX(List<?> collectionX){ ... synchronized(collectionX) { ... eg adding to the list } ... synchronized(collectionX) { ... eg updating an element } } 
+4
source

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


All Articles