0

すべて、多くのスレッドによって呼び出される API 呼び出しがあります。唯一の問題は、遅延ベットです。スレッドは 1 秒以上にする必要があります。同期ブロックなしで、1 つのスレッドが時間 t1 に API を呼び出している場合、他のすべてのスレッドは 1 秒間待機し、他のすべてのスレッドは t1 + 1 秒で API を呼び出します。これは私が望んでいないので、1 つのスレッドが他のすべてのスレッド ブロックを待機している限り、待機ブロック全体を同期ブロックに入れます。

これは機能します。ただし、これは最も効率的な方法ではないと思います。

任意の推奨事項は大歓迎です。

private static volatile AtomicLong lastAPICall = new AtomicLong();

private void callAPI() {

  // 1 sec plus a little extra
  final long oneMS = 1 * 1000 + 100;            
  long lastCall = 0;
  long timeDiff = 0;

  synchronized (lastAPICall) {
       timeDiff = System.currentTimeMillis() - lastAPICall.get();
       lastCall = lastAPICall.getAndSet(System.currentTimeMillis());
   }
}

if (System.currentTimeMillis() - lastCall < oneMS) {
    synchronized (lastAPICall) {
            try {
                long sleep = oneMS - timeDiff;
                Thread.sleep(oneMS - timeDiff);
            } catch (InterruptedException ignore) {}
            finally {
               lastAPICall.set(System.currentTimeMillis());
               log.info("Thread: " + Thread.currentThread().getId() + " calling the api at this time: " +   System.currentTimeMillis());
        }
  }
}

try {
// API CALL
}
catch (IOException t){
            throw t;
} finally {
   synchronized (lastAPICall) {
     lastAPICall.set(System.currentTimeMillis());   
  }
}

// Log files for running the code with 4 threads
Thread: 35 calling the api at this time: 1456182353694
Thread: 34 calling the api at this time: 1456182354795
Thread: 37 calling the api at this time: 1456182355905
Thread: 36 calling the api at this time: 1456182357003
4

1 に答える 1