-
Notifications
You must be signed in to change notification settings - Fork 2.3k
Background with serial not working #1775
Description
The Background annotation with serial does not work always as expected, in the case, when it's called from another background thread.
It is expected that methods annotated with the @background(serial = X) annotation (provided X is the same for all of them) will run in the order that they were called.
Example
package org.androidannotations.sample;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import android.app.Activity;
import android.util.Log;
@EActivity(R.layout.my_activity)
public class MyActivity extends Activity {
@Click
void myButtonClicked() {
bgTaskCallingOthers();
}
@Background
void bgTaskCallingOthers() {
// we expect that first the long finishes, then the short.
backgroundSerialLong();
backgroundSerialShort();
}
@Background(serial = "same")
void backgroundSerialShort() {
Log.w("MyActivity", "Background serial short finished");
}
@Background(serial = "same")
void backgroundSerialLong() {
try {
Thread.sleep(5000);
} catch (InterruptedException ex) {
// ignore
} finally {
Log.w("MyActivity", "Background serial long finished");
}
}
}In the above example, we expect that first the backgroundSerialLong method then the second backgroundSerialShort method prints it's log message.
But sometimes it's the other way around, resulting in the following log:
05-19 08:24:49.480 15669-15839/org.androidannotations.sample W/MyActivity: Background serial short finished
05-19 08:24:54.480 15669-15765/org.androidannotations.sample W/MyActivity: Background serial long finished
My first thought, is that sometimes the executor starts to run the task immediately, which in it's first line calls managed.getAndSet(true), so in BackgroundExecutor.execute(Task task), in the second if, the task is not added to the TASKS field.
Because of this, the second background task, doesn't know about the first one.
UPDATE
I've tested this by calling the aforementioned two methods from the myButtonClicked method (which runs on the main thread) and the same thing happens. Sometimes it works, sometimes it doesn't. Around 2 out of 5 times it fails.