I got the trouble with using synchronized the object in background thread. I've specified the problem in sample nutshell:
I write the simple class like that:
public class UIThreadClass { MyObject object; UIThreadClass() { object = new MyObject(); object.doActionOne(); object.doActionTwo(); } }
Now my task is improve the code by put two method to non-UI thread. I am using AsyncTask
For doActionOne()
private static class DoActionOneTask extends AsyncTask<Void, Void, Void> { private WeakReference<MyObject> wObject; DoActionOneTask(MyObject object) { wObject = new WeakReference<>(object); } @Override protected Void doInBackground(Void... voids) { if(wObject.get() != null) { MyObject myObject = wObject.get(); myObject.doActionOne(); } return null; } }
For doActionTwo()
private static class DoActionTwoTask extends AsyncTask<Void, Void, Void> { private WeakReference<MyObject> wObject; DoActionOneTask(MyObject object) { wObject = new WeakReference<>(object); } @Override protected Void doInBackground(Void... voids) { if(wObject.get() != null) { MyObject myObject = wObject.get(); myObject.doActionTwo(); } return null; } }
Now call them in UI thread
public class UIThreadClass { MyObject object; UIThreadClass() { object = new MyObject(); new DoActionOneTask(object).execute(); new DoActionTwoTask(object).execute(); } }
The question is:
When using AsyncTask - how to synchronized the object to make sure that the doActionTwo() alway call after doActionOne() method ?.
I have tried using synchronized (myObject) {myObject.doActionOne();} in doInBackground() but the system is warning me that myObject just local variable and it is difficult to guarantee correctness.
Can anyone help me this situation ? Thanks a lot!