http リクエストのキューを最初から実装しようとすると問題が発生します。申し訳ありませんが、これは誰かにとって非常に単純な並行性の問題かもしれません。
基本的に、アプリケーションで一度に 1 つのリクエストのみを実行したいと考えています。追加のリクエストはキューに入れられ、後で実行されます。
FutureTask や Execution pool などの他の高度な機能については認識していますが、基本的な同時実行の問題を解決する方法に興味があるため、回答が必要です。以下は私のクラスがrequestQueueを維持することです
private Queue<HttpRequest> requestQueue;
private AsyncTask myAsyncTask=null;
public boolean send(HttpRequest hr){
//if there isn't existing task, start a new one, otherwise just enqueue the request
//COMMENT 1.
if(myAsyncTask==null){
requestQueue.offer(hr);
myAsyncTask= new RequestTask();
myAsyncTask.execute(null);
return true;
}
else{
//enqueue
//COMMENT 2
requestQueue.offer(hr);
}
}
//nested class
RequestTask extends AsyncTask<boolean,void,void>{
protected HttpResponse doInBackground(void... v){
//send all request in the queue
while(requestQueue.peek != null){
HttpResquest r= requestQueue.poll
//... leave out code about executing the request
}
return true;
}
protected void doPostExecute(boolean success){
//COMMENT 3: if scheduler stop here just before myAsyncTask is set to null
myAsyncTask=null;
}
}
問題は、スレッド スケジューラがポイント 3 (myAsyncTask が null に設定される直前) でバックグラウンド スレッドを停止するかどうかです。
//COMMENT 3: if scheduler stop here just before myAsyncTask is set to null
myAsyncTask=null;
このとき、他のスレッドがたまたま COMMENT 1 のポイントに移動し、if ... else ... ブロックに入ります。myAsyncTask が null に設定されていないため、タスクは else ブロック (コメント 2) でキューに入れられますが、新しい asyncTask は作成されず、キューがスタックします!
//COMMENT 1.
if(myAsyncTask==null){
requestQueue.offer(hr);
myAsyncTask= new RequestTask;
myAsyncTask.execute(null);
return true;
}
else{
//enqueue
//COMMENT 2
requestQueue.offer(hr);
}
明確であることを願っています。キューの処理が停止する可能性があります。これを回避する方法を知りたいです。前もって感謝します