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 seems work for me right now, but I am not familiar with threading(it always confuse me), should I do it like above code any way?
This looks to be a spin loop which will use unnecessary CPU. It is better to use
waitandnotifyto signal that the data has been fetched. Something like:I don’t think you need a fetched
AtomicBooleanat all. You should make therowCountbevolatileand then you can test its value. Thewhileloop is a good pattern to follow because of producer/consumer race conditions and spurious interrupts.