I have a method and inside this method I have a block:
public void method()
{
[block instructions]
}
But this method is called twice in
Marko's answer is simple conceptually, but every call to method now needs to perform an atomic operation on the AtomicBoolean. If method() is very commonly called, this will incur a significant performance penalty.
Here's another thread-safe solution I came up with, based on the singleton pattern. I expect this to have significantly less performance overhead.
public class MyClass {
public void method() {
BlockRunner.runIfFirst();
}
private static class BlockRunner {
static {
[block insturctions]
}
public static void runIfFirst() {}
}
}
This solution is based on the Singleton lazy-init concept described here.
If my understanding is correct, when BlockRunner is first invoked by calling runIfFirst(), the static block of code will get invoked. All future calls to runIfFirst() will simply just return immediately, without any real code being executed. From a performance perspective, you're replacing a heavy atomic operation, with a simple branch-and-return operation.