Block the current thread for execution until the variable is updated by another thread

my code:

    private  AtomicBoolean fetched1 = new AtomicBoolean(false);

    private int  rowCount;

    public int getRowCount() {
            data.getRealm().exec(new Runnable(){
                @Override
                public  void run() {
                    rowCount = data.size();
                    fetched1.set(true);
                }
            });
            while(!fetched1.get()){
            }
            fetched1.set(false);
            return rowCount;
        }

      

It looks like it works for me right now, but I'm not familiar with threading (it always confuses me), should I do it like above in some way?

+3


source to share


2 answers


Should I do it like the code above?

It looks like a spinning loop that will use unnecessary processor. Better to use wait

and notify

to signal that data has been retrieved. Something like:



   private final Object lock = new Object();
   private volatile Integer rowCount = null;
   ...

      public void run() {
         rowCount = data.size();
         synchronized (lock) {
            lock.notify();
         }
      }

  synchronized (lock) {
     // we loop here in case of race conditions or spurious interrupts
     while (rowCount == null) {
        lock.wait();
     }
  }
  ...

      

I don't think you need to get it AtomicBoolean

at all. You have to do rowCount

be volatile

and then check its value. Cycle while

is a good pattern to follow due to producer / consumer conditions and spurious interrupts.

+7


source


You have two problems.

  • the first thread is busy waiting, which is usually undesirable.
  • the template cannot be expanded to more threads, as the second thread might try to set to true.


Instead, the simplest pattern is to lock an object and wait / notify when a value changes.

+4


source







All Articles