fix bug: Under high concurrency, Mqtt client nextMessageId exceeds the 0xffff limit (#2564)

The compareAndSet method and getAndIncrement method of the AtomicInteger class are atomic, but when these two methods are used at the same time, they are no longer atomic.
This commit is contained in:
blackstar-baba 2020-04-01 14:39:51 +08:00 committed by GitHub
parent d94cb9ca47
commit 00b5d36e0b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -407,8 +407,12 @@ final class MqttClientImpl implements MqttClient {
}
private MqttMessageIdVariableHeader getNewMessageId() {
this.nextMessageId.compareAndSet(0xffff, 1);
return MqttMessageIdVariableHeader.from(this.nextMessageId.getAndIncrement());
int messageId;
synchronized (this.nextMessageId) {
this.nextMessageId.compareAndSet(0xffff, 1);
messageId = this.nextMessageId.getAndIncrement();
}
return MqttMessageIdVariableHeader.from(messageId);
}
private Future<Void> createSubscription(String topic, MqttHandler handler, boolean once, MqttQoS qos) {