user1508419 user1508419 - 4 years ago 124
Java Question

Call a block of a method only for the first call of the method

I have a method and inside this method I have a block:

public void method()
{
[block instructions]
}


But this method is called twice in my program. I would like this block to be executed only one time and only for the first occurrence of the method. What would be the best and elegant way to do that?

Answer Source
private static final AtomicBoolean hasRunAtom = new AtomicBoolean();

public void method() {
  if (hasRunAtom.getAndSet(true)) return;
  [block instructions]
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download