Hide Rc.countBorrows

The state that people really care about is whether or not an Rc has ownership.
Exposing the reference count will probably just confuse people.
The reference count is still exposed on RcSupport because it may be (and is, in the case of ByteBufAdaptor) needed to support implementation details.
This commit is contained in:
Chris Vest 2021-05-07 10:54:04 +02:00
parent 83643a5dc9
commit ef714c90d9
4 changed files with 22 additions and 18 deletions

View File

@ -78,11 +78,6 @@ public abstract class BufferHolder<T extends BufferHolder<T>> implements Rc<T> {
return buf.isOwned();
}
@Override
public int countBorrows() {
return buf.countBorrows();
}
@SuppressWarnings("unchecked")
@Override
public Send<T> send() {

View File

@ -69,15 +69,6 @@ public interface Rc<I extends Rc<I>> extends AutoCloseable {
*/
boolean isOwned();
/**
* Count the number of borrows of this object.
* Note that even if the number of borrows is {@code 0}, this object might not be {@linkplain #isOwned() owned}
* because there could be other restrictions involved in ownership.
*
* @return The number of borrows, if any, of this object.
*/
int countBorrows();
/**
* Check if this object is accessible.
*

View File

@ -106,7 +106,13 @@ public abstract class RcSupport<I extends Rc<I>, T extends RcSupport<I, T>> impl
return acquires == 0;
}
@Override
/**
* Count the number of borrows of this object.
* Note that even if the number of borrows is {@code 0}, this object might not be {@linkplain #isOwned() owned}
* because there could be other restrictions involved in ownership.
*
* @return The number of borrows, if any, of this object.
*/
public int countBorrows() {
return Math.max(acquires, 0);
}

View File

@ -24,6 +24,7 @@ import io.netty.buffer.SlicedByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.buffer.api.Buffer;
import io.netty.buffer.api.BufferAllocator;
import io.netty.buffer.api.RcSupport;
import io.netty.util.ByteProcessor;
import io.netty.util.IllegalReferenceCountException;
@ -212,13 +213,13 @@ public final class ByteBufAdaptor extends ByteBuf {
public ByteBuf ensureWritable(int minWritableBytes) {
checkAccess();
if (writableBytes() < minWritableBytes) {
int borrows = buffer.countBorrows();
try {
if (borrows == 0) {
if (buffer.isOwned()) {
// Good place.
buffer.ensureWritable(minWritableBytes);
} else {
// Highly questionable place, but ByteBuf technically allows this, so we have to emulate.
int borrows = countBorrows();
release(borrows);
try {
buffer.ensureWritable(minWritableBytes);
@ -1650,7 +1651,18 @@ public final class ByteBufAdaptor extends ByteBuf {
@Override
public int refCnt() {
return buffer.isAccessible()? 1 + buffer.countBorrows() : 0;
return 1 + countBorrows();
}
private int countBorrows() {
if (!buffer.isAccessible()) {
return -1;
}
if (buffer instanceof RcSupport) {
var rc = (RcSupport<?, ?>) buffer;
return rc.countBorrows();
}
return buffer.isOwned()? 0 : 1;
}
@Override