Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is is possible to make a method execute only once?

Tags:

I have a for loop and structure like this:

for(....)
....
....
if(isTrue)
... do something..
.. method to be executed once (doTrick) is declared outside for loop.
....endif
endfor

public void doTrick()
...
...
..end

Is it possible for a method in for loop to be executed only once?

like image 354
Gandalf StormCrow Avatar asked Apr 19 '10 08:04

Gandalf StormCrow


People also ask

How do I make a function run only once in Java?

We can apply concepts similar to our debounce utility to execute a function once and only one time. function execOnce(fn, context) { var result; return function () { if (fn) { result = fn. apply(context || this, arguments); fn = null; } return result; }; } function sayHello() { console.

How do you call a method only once on Android?

You can do this, by using shared preferences . Store a value in shared preferences: SharedPreferences prefs = getPreferences(MODE_PRIVATE); SharedPreferences. Editor editor = prefs.


2 Answers

Sure!..

if(!alreadyExecuted) {
    doTrick();
    alreadyExecuted = true;
}
like image 128
Rosdi Kasim Avatar answered Oct 03 '22 18:10

Rosdi Kasim


Your can use AtomicBoolean to make sure the task is only called the first time:

import java.util.concurrent.atomic.AtomicBoolean;

public class Once {
    private final AtomicBoolean done = new AtomicBoolean();
    
    public void run(Runnable task) {
        if (done.get()) return;
        if (done.compareAndSet(false, true)) {
            task.run();
        }
    }
}

Usage:

Once once = new Once();
once.run(new Runnable() {
    @Override
    public void run() {
        foo();
    }
});

// or java 8
once.run(() -> foo());
like image 37
Hover Ruan Avatar answered Oct 03 '22 18:10

Hover Ruan