BewareMyPower commented on code in PR #25110:
URL: https://github.com/apache/pulsar/pull/25110#discussion_r2672329694
##########
managed-ledger/src/main/java/org/apache/bookkeeper/mledger/impl/ManagedCursorImpl.java:
##########
@@ -1243,14 +1243,17 @@ public boolean hasMoreEntries() {
@Override
public long getNumberOfEntries() {
- if (readPosition.compareTo(ledger.getLastPosition().getNext()) > 0) {
+ Position readPos = readPosition;
+ Position lastPosition = ledger.getLastPosition();
+ Position nextPosition = lastPosition.getNext();
Review Comment:
Copying the positions into local variables is not enough if these variables
can be modified in a different thread. We should add a lock to guarantee thread
safety.
Here is an example of a very simple case:
```java
class Range {
private int start = 0;
private int end = 0;
public int getNumberOfEntries() {
return end - start;
}
public void produce(int n) {
CompletableFuture.runAsync(() -> {
end += n;
});
}
public void consume(int n) {
CompletableFuture.runAsync(() -> {
if (start + n > end) {
throw new IllegalStateException("Cannot consume more than
produced");
}
start += n;
});
}
}
```
Even if you changed `getNumberOfEntries()` to:
```java
private volatile int start = 0;
private volatile int end = 0;
public int getNumberOfEntries() {
int end = this.end;
int start = this.start;
return end - start;
}
```
`getNumberOfEntries` is still not safe
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]