Q:

Change Optional from within it self

I have a variable oneTimeTask. Its type is:
Optional<Runnable> oneTimeTask=...;

Do you think this example is a dirty way to 'reset' the Optional<Runnable>:
oneTimeTask = Optional.of(() ->  {
            /*Run task
            ...*/
            oneTimeTask= Optional.empty();
        });

... what do you think?
oneTimeTask will get a Optional(someRunnable) value many times while the app is running, but most of the time the value is empty.
Should I maybe use a Supplier<Runnable> or Supplier<Optional<Runnable>> instead?
If yes, how would you implement it? (I'm not so familiar with the Supplier class)
I'm open for any alternative (better) ways there achieve the same result.

A:

As you want to control what is returned from one call to the next you want a Supplier.
AtomicBoolean once = new AtomicBoolean();
Supplier<Runnable> oneTimeTask = () -> once.getAndSet(true) 
                                     ? () -> {} 
                                     : () -> { /* do one */ };

or more simply you can have a Runnable
Runnable runs = () -> {
    if (once.getAndSet(true)) return;
    /* do once */
};

