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

后端 未结 6 1722
后悔当初
后悔当初 2021-01-20 02:54

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

public void method()
{
   [block instructions]
}

But this method is called twice in

6条回答
  •  情话喂你
    2021-01-20 03:16

    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.

提交回复
热议问题