私は、メソッドが(コールバックではなく)すぐにデータを必要とする(GoogleMapsタイルプロバイダの)インタフェース実装を持っているが、私がデータを取得するためにコールバックのデータを返すメソッドを呼び出さなければなりません。私はこれらの2つを結びつけなければならないし、何か(私はまだ動作していると思うがまだテストしていない)があるが、私はAndroidスタジオの警告を心配している。ローカル最終変数で同期を使用する
これは私が書いたコードです:
@Override
public Tile getTile(int x, int y, int zoom) {
// If the tile provider is not available, return null
if(tileProvider == null) {
return NO_TILE;
}
// Define the tile request
final TileRequest tileRequest = new TileRequest(tileProvider.getLayer().getTileWidth(), tileProvider.getLayer().getTileHeight());
// Make the call to get the tile data, which, depending on the situation, can possibly
// be handled by another thread.
tileProvider.getTile(x, y, zoom, new GetDataListener<byte[]>() {
@Override
public void onGetData(byte[] data, Exception exception) {
synchronized (tileRequest) {
tileRequest.data = data;
tileRequest.exceptionOccurred = exception != null;
tileRequest.finishedRequest = true;
tileRequest.notify();
}
}
});
synchronized (tileRequest) {
// If, before this statement was reached, the request has already been finished, call and return getTile immediately.
if(tileRequest.finishedRequest) {
return tileRequest.getTile();
} else {
try {
// Wait for the tileRequest to be finished
tileRequest.wait();
// Once it is finished (in the callback a notify is called as soon as its finished, so thats how this code is reached)
// the tile data is available, return the tile
return tileRequest.getTile();
} catch(InterruptedException ex) {
// Exception occurred, return null so GoogleMaps will try it again later
logger.error("Exception in getTile method: {}", ex.getLocalizedMessage());
ex.printStackTrace();
return null;
}
}
}
}
だから何のAndroid Studioは、二synchronized (tileRequest) {
ライン上で、私を与えていることは次の警告である:
Synchronization on local variable 'tileRequest'
Reports synchronization on a local variable or parameter. Such synchronization has little effect, since different threads usually will have different values for the local variable or parameter. The intent of the code will usually be clearer if synchronization on a field is used.
同期の私の理解にはあまりにも自信がない、待っていると通知するので、誰かが電話することができます私のアプローチが有効であれば、私は警告に関係なく有効ですか?何の複数のスレッドが関与しなかったことを示すいくつかの質問がありました
EDIT 、私はコメントを少し更新しますが、tileProvider.getTile(...)メソッドは、タイルを取得しますが、これは保証はありません別のスレッドでは発生しません。
tileProvider.getTile(...)は、データを別のスレッドで取得するコールバック内のデータを返します。だからそれはマルチスレッドになります。 –
どういう意味ですか?私がtileProvider.getTile(...)を持っていた理由は、リクエストを別のスレッドに委譲できるようにコールバックを使用して結果を返すためです。 –
あなたは何を意味するのか分かります。 – assylias