I have an AsyncTask application called UploadManager in an Android application that checks processed items and uploads them to the server.
For this I use ScheduledExecutorService.scheduleAtFixedRate to check items every 1 minute and upload them to the server.
However, from time to time several thread pools are created (this happens in about 10% of cases), because of which sometimes the same request is sent twice to the server, although this concurrency is processed both on the server and on the server at the client level, but I still don't want this to happen on the client side.
Below is what the code looks like.
In MainActivity (start-activity), I run UploadManager as:
public class MainActivity extends BaseActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); . . . new UploadManager().execute(this); } }
UploadManager works as follows:
public class UploadManager extends AsyncTask<Context, Integer, Integer> { private ScheduledExecutorService scheduledExecutorService; private static final int NUM_OF_THREADS = 5; private static final int DELAY_IN_SECONDS = 60; private Context context; private final Logger logger = new Logger(getClass().getSimpleName()); protected Integer doInBackground(Context... context) { this.context = context[0]; scheduledExecutorService = Executors.newScheduledThreadPool(NUM_OF_THREADS); scheduledExecutorService.scheduleAtFixedRate(postInformation, 5, DELAY_IN_SECONDS, TimeUnit.SECONDS); return 0; } private Runnable postInformation = new Runnable() { @Override public void run() { if (NetworkManager.isInternetAvailable(context)) { uploadAcknowledgement(); } } }; private void uploadAcknowledgement() { List<Acknowledgement> ackList = null; try { logger.info("RUNNING TASK TO POST ACKNOWLEDGEMENT"); . . } } }
When I checked the logs, he says:
35119 [pool-2-thread-1] INFO Upload Manager - [1363841355530] : 21/03/2013 10:19:15 : RUNNING TASK TO POST ACKNOWLEDGEMENT 35122 [pool-3-thread-1] INFO Upload Manager - [1363841355532] : 21/03/2013 10:19:15 : RUNNING TASK TO POST ACKNOWLEDGEMENT
Which clearly indicates that there are now several thread pools that cause the uploadAcknowledgement() method to uploadAcknowledgement() called multiple times.
MainActivity is declared in AndroidManifest.xml as:
<application android:label="@string/app_name" android:icon="@drawable/icon"> <activity android:name="MainActivity" android:label="@string/app_name" android:theme="@android:style/Theme.NoTitleBar"> <intent-filter> <action android:name="android.intent.action.MAIN"/> <category android:name="android.intent.category.LAUNCHER"/> <action android:name="android.net.conn.CONNECTIVITY_CHANGE"/> </intent-filter> </activity> . .
source share