In Java, you can achieve them with a flag.
As you mentioned in you question, you can check the function is called or not with a flag. But beware of the thread-safety problem. Your function may be called over once if your code is not thread-safety. For example, you may write a code like this:
class NotThreadSafety {
private static boolean isFunctionCalled = false;
public static void shouldOnlyCalledOnce() {
if (!isFunctionCalled) {
System.out.println("I think I should called only once!!");
isFunctionCalled = true;
}
}
}
If you called this function in multi-threads like this:
ExecutorService exec = Executors.newCachedThreadPool();
for(int i = 0; i != 5; ++i) {
exec.execute(new Runnable() {
@Override
public void run() {
NotThreadSafety.shouldOnlyCalledOnce();
}
});
}
exec.shutdown();
You output may be like:
I think I should called only once!!
I think I should called only once!!
I think I should called only once!!
I think I should called only once!!
I think I should called only once!!
You need to add synchronized
keyword to shouldOnlyCalledOnce()
function, it will prevent race condition on isFunctionCalled
field.