Issue
My application is collecting data from sensors and I have the user manually save labels. Whenever the user touches a button to save a label, I run an AsyncTask and inside the doInBackground method, I'm calling a synchronized method whose unique purpose is to save the information in a file. The method is part of a helper library so I access it through as a static method, so it is a synchronized static method. I need the labeling to saved in the order it was entered. However, I noticed that sometimes the labels are saved in a different order which tells me that the synchronized method might not be working as expected
- Is there any restriction for synchronized methods within AsyncTasks?
- Is there any better way to accomplish this? I mean, keep saving the data in a background thread but ensuring that if we have multiple, I execute them in the order they arrived?
The code looks a little like this:
public class FileUtil {
public static synchronized void saveActivityDataToFile() throws IOException{
//Saving file code
}
}
//This asynctask is called everytime the user touches the button
private class SaveDataInBackground extends AsyncTask<String, Integer, Void> {
public SaveDataInBackground(){
}
protected Void doInBackground(String... lists) {
try {
//I expect this to run on its own thread but synchronously if this asynctask is called multiple times withing a short interval of time
FileUtil.saveActivityDataToFile();
}catch (IOException e){
Log.e(TAG,"Error while saving activity: " + e.getMessage());
}
return null;
}
protected void onPostExecute(Void v) {
}
}
Solution
- There are no any restrictions for synchronized methods in
AsyncTasks
Btw synchronized is not about order, its about blocking part of code for only one thread in time. So there can be situation:
Task 1 started
Task 2 started
Task 2 write and finish
Task 1 write and finish
- You could use
Thread
instead ofAsyncTask
. And then useThreadPoolExecutor
with only one thread or usethread.join()
But better to use RxJava2
or Kotlin Coroutines
for such things
Answered By - Andrey Danilov
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.