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?
source to share
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.
source to share