Set element synchronization in java

I have a set of unique elements. Each element has a set of operations that it can perform, but the operations of each element are independent of other operations with the elements. For example, there are three operations: O1, O2, O3, which each element can perform. Now each element can execute O1, O2, O3, without conflict with another element. But each element when performing the operation should exclusively perform O1, O2, O3 (one at a time).

This is a good way to lock an item in this case. Will this work? Is there any other way, e.g. with ReentrantLock or with java8, to make it better?

For instance,

for(Element element : elements) {
 synchronized(element) {
   //Perform O1,O2,O3 but one at a time
 }
}

Suppose that the above for the loop can be called from several places, and this for the loop is written in several places in the code to perform various work of the element.

+4
source share
1 answer

As the label space indicates, the safest option is likely to do your operations synchronized, rather than relying on all the callers to do it right, for example:

public class Element {
  public synchronized void O1() { ... }
  public synchronized void O2() { ... }
  public synchronized void O3() { ... }
}

This ensures that for a given instance, Elementonly one operation is called at a time. Then, your subscribers do not need to worry about explicitly synchronizing anything:

for(Element element : elements) {
  element.O1();
  element.O2();
  element.O3();
}

, , (O1, O2 O3) , . Element, , , , :

public class Element {
  // ...
  public synchronized void doAllOperations() { O1(); O2(); O3(); }
}

, doAllOperations() .

0

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


All Articles