Make NettyTransportClient.getCurrentId() thread safe (#1707)

Fix issue #1705.

- Use CAS to make it thread safe and limited in the declared range.

Signed-off-by: cj <power4j@outlook.com>
This commit is contained in:
cj 2020-09-14 23:23:00 +08:00 committed by GitHub
parent b7b54034cc
commit 34fc435ce5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 7 additions and 4 deletions

View File

@ -238,10 +238,12 @@ public class NettyTransportClient implements ClusterTransportClient {
} }
private int getCurrentId() { private int getCurrentId() {
if (idGenerator.get() > MAX_ID) { int pre, next;
idGenerator.set(0); do {
} pre = idGenerator.get();
return idGenerator.incrementAndGet(); next = pre >= MAX_ID ? MIN_ID : pre + 1;
} while (!idGenerator.compareAndSet(pre, next));
return next;
} }
/*public CompletableFuture<ClusterResponse> sendRequestAsync(ClusterRequest request) { /*public CompletableFuture<ClusterResponse> sendRequestAsync(ClusterRequest request) {
@ -266,5 +268,6 @@ public class NettyTransportClient implements ClusterTransportClient {
return future; return future;
}*/ }*/
private static final int MIN_ID = 1;
private static final int MAX_ID = 999_999_999; private static final int MAX_ID = 999_999_999;
} }