How to ensure that a block of code is executed only once in a multi-threaded environment?

I do not have a single actor who creates an object that I want to create only once. How is this achieved? Can an actor be single? If so, how?

class NonSingletonActor extends UntypedActor {

   public static onReceive(Object arg)  throws Exception {

         *block of code that needs to be executed once!*
} }
+4
source share
3 answers

These other answers seem to have neglected the fact that your question is asked in the context of Akka Akka.

If you have an object that you want to reference from several participants, but only created once, you must delegate these operations to another actor - the actor who will create and manage the object in question - and then share the link to this object with the actor.

a NonSingletonActor , , . Akka , , - .

+3

AtomicBoolean , compareAndSet. : "" . : (a) , , (b) , (c) true, ( , ).

private static final AtomicBoolean hasRun = new AtomicBoolean(false);

...
if (hasRun.compareAndSet(false, true)) {
    // your code here
}

, hasRun "false" ( ). , "true" if; if. , check-and-set ( ), , ; true, "" .

+7

, :

class NonSingletonActor extends UntypedActor {

  private static volatile boolean executed;

  public static onReceive(Object arg)  throws Exception {
    if (executed)
      return;

    synchronized (NonSingletonActor.class) {
      if (executed)
        return; 

      executed= true; 
      *block of code that needs to be executed once!*
    }
  } 
}

, true .

0
source

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


All Articles