Search code examples
codenameone

Best way to wait until a variable changes its value


I realize that what I'm about to ask is more a generic Java question than a specific Codename One question, anyway, considering that the reference APIs are Codename One's, is there a more elegant and more reliable way to handle a situation like the following code? Such cases happen if I need to synchronously make code that by its nature would be asynchronous with callback:

while (lock) {
   CN.invokeAndBlock(() -> Util.sleep(500));
}

I quoted a code like that here: https://github.com/codenameone/CodenameOne/issues/3192


Solution

  • JavaSE has some pretty cool features to do that but we don't support them at this time e.g. CountDownLatch.

    But this is still pretty easy to do:

    public class SharedVar<T> {
        private T var;
        public T get() { return var; }
        public synchronized void set(T var) {
           this.var = var;
           notifyAll();
        }
        public synchronized T waitForChange() {
           wait();
           return var;
        }
    }