Java Code Examples for io.netty.buffer.ByteBuf#refCnt()

The following examples show how to use io.netty.buffer.ByteBuf#refCnt() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: InMemoryResumableFramesStore.java    From rsocket-java with Apache License 2.0 6 votes vote down vote up
void saveFrame(ByteBuf frame) {
  if (upstreamFrameRefCnt == 0) {
    upstreamFrameRefCnt = frame.refCnt();
  }

  int frameSize = frame.readableBytes();
  long availableSize = cacheLimit - cacheSize;
  while (availableSize < frameSize) {
    ByteBuf cachedFrame = cachedFrames.poll();
    if (cachedFrame != null) {
      availableSize += releaseTailFrame(cachedFrame);
    } else {
      break;
    }
  }
  if (availableSize >= frameSize) {
    cachedFrames.offer(frame.retain());
    cacheSize += frameSize;
  } else {
    position += frameSize;
  }
}
 
Example 2
Source File: Decoder.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public final void channelRead(ChannelHandlerContext context, Object message) throws Exception {
  if (message instanceof ByteBuf) {
    ByteBuf input = (ByteBuf)message;
    try {
      messageReceived(context, input);
    }
    finally {
      // client should release buffer as soon as possible, so, input could be released already
      if (input.refCnt() > 0) {
        input.release();
      }
    }
  }
  else {
    context.fireChannelRead(message);
  }
}
 
Example 3
Source File: DefaultWriterListener.java    From nettythrift with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings({ "rawtypes" })
@Override
public void beforeWrite(TMessage msg, TBase args, TBase result) {
	// reuse message's buffer when write? yes, we use the pool.
	ByteBuf readedBuf = message.getContent();
	int refCount = readedBuf.refCnt();
	if (refCount > 0) {
		readedBuf.release(refCount);
	}
	// voidMethod's return message is very short
	int initialCapacity = serverDef.trafficForecast.getInitBytesForWrite(msg.name);
	// logger.debug("initialCapacity = {} , msg = {}",initialCapacity, msg);
	ByteBuf buf = ctx.alloc().buffer(initialCapacity, serverDef.maxFrameSize);
	message.setContent(buf).beforeWrite(ctx);
	transport.setOutputBuffer(buf);
}
 
Example 4
Source File: BufferAllocatorsTest.java    From servicetalk with Apache License 2.0 6 votes vote down vote up
private static void assertByteBufIsUnreleasable(ByteBuf byteBuf) {
    int refCnt = byteBuf.refCnt();

    // Expect greater than 0 as some operations may return Unpooled.EMPTY_BUFFER with refCnt == 1
    assertThat(refCnt, greaterThan(0));

    byteBuf.release();
    assertEquals(refCnt, byteBuf.refCnt());

    byteBuf.release(1);
    assertEquals(refCnt, byteBuf.refCnt());

    byteBuf.retain();
    assertEquals(refCnt, byteBuf.refCnt());

    byteBuf.retain(1);
    assertEquals(refCnt, byteBuf.refCnt());
}
 
Example 5
Source File: DegelationTransferBuilder.java    From sissi with Apache License 2.0 6 votes vote down vote up
@Override
public DelegationTransfer transfer(TransferBuffer buffer) {
	ByteBuf buf = ByteBuf.class.cast(buffer.getBuffer());
	try {
		this.lock.lock();
		int readable = buf.readableBytes();
		buf.readBytes(this.output, readable);
		this.readable.addAndGet(readable);
		return this;
	} catch (Exception e) {
		DegelationTransferBuilder.this.log.error(e);
		Trace.trace(DegelationTransferBuilder.this.log, e);
		throw new RuntimeException(e);
	} finally {
		this.lock.unlock();
		if (buf.refCnt() > 0) {
			ReferenceCountUtil.release(buf);
		}
	}
}
 
Example 6
Source File: FSDelegation.java    From sissi with Apache License 2.0 6 votes vote down vote up
@Override
public TransferBuffer release() {
	try {
		ByteBuf byteBuf = this.queue.take();
		if (byteBuf.refCnt() > 0) {
			ReferenceCountUtil.release(byteBuf);
		}
	} catch (Exception e) {
		FSDelegation.this.log.warn(e.toString());
		Trace.trace(FSDelegation.this.log, e);
	} finally {
		this.notify();
		FSDelegation.this.resourceCounter.decrement(FSDelegation.this.chunk);
	}
	return this;
}
 
Example 7
Source File: AbstractBatchDecoder.java    From sofa-bolt with Apache License 2.0 6 votes vote down vote up
@Override
public ByteBuf cumulate(ByteBufAllocator alloc,
                        ByteBuf cumulation,
                        ByteBuf in) {
    ByteBuf buffer;
    if (cumulation.writerIndex() > cumulation
        .maxCapacity()
                                   - in.readableBytes()
        || cumulation.refCnt() > 1) {
        // Expand cumulation (by replace it) when either there is not more room in the buffer
        // or if the refCnt is greater then 1 which may happen when the user use slice().retain() or
        // duplicate().retain().
        //
        // See:
        // - https://github.com/netty/netty/issues/2327
        // - https://github.com/netty/netty/issues/1764
        buffer = expandCumulation(alloc,
            cumulation,
            in.readableBytes());
    } else {
        buffer = cumulation;
    }
    buffer.writeBytes(in);
    in.release();
    return buffer;
}
 
Example 8
Source File: GatewayWebsocketHandler.java    From Discord4J with GNU Lesser General Public License v3.0 5 votes vote down vote up
private static void safeRelease(ByteBuf buf) {
    if (buf.refCnt() > 0) {
        try {
            buf.release();
        } catch (IllegalReferenceCountException e) {
            if (log.isDebugEnabled()) {
                log.debug("", e);
            }
        }
    }
}
 
Example 9
Source File: MqttPublishMessage.java    From mithqtt with Apache License 2.0 5 votes vote down vote up
@Override
public ByteBuf content() {
    final ByteBuf data = (ByteBuf) super.payload();
    if (data.refCnt() <= 0) {
        throw new IllegalReferenceCountException(data.refCnt());
    }
    return data;
}
 
Example 10
Source File: VertxBlockingOutput.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Override
public void write(ByteBuf data, boolean last) throws IOException {
    if (last && data == null) {
        request.response().end();
        return;
    }
    try {
        //do all this in the same lock
        synchronized (request.connection()) {
            try {
                awaitWriteable();
                if (last) {
                    request.response().end(createBuffer(data));
                } else {
                    request.response().write(createBuffer(data));
                }
            } catch (Exception e) {
                if (data != null && data.refCnt() > 0) {
                    data.release();
                }
                throw new IOException("Failed to write", e);
            }
        }
    } finally {
        if (last) {
            terminateResponse();
        }
    }
}
 
Example 11
Source File: VertxOutputStream.java    From quarkus with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public void write(final byte[] b, final int off, final int len) throws IOException {
    if (len < 1) {
        return;
    }
    if (closed) {
        throw new IOException("Stream is closed");
    }

    int rem = len;
    int idx = off;
    ByteBuf buffer = pooledBuffer;
    try {
        if (buffer == null) {
            pooledBuffer = buffer = allocator.allocateBuffer();
        }
        while (rem > 0) {
            int toWrite = Math.min(rem, buffer.writableBytes());
            buffer.writeBytes(b, idx, toWrite);
            rem -= toWrite;
            idx += toWrite;
            if (!buffer.isWritable()) {
                ByteBuf tmpBuf = buffer;
                this.pooledBuffer = buffer = allocator.allocateBuffer();
                response.writeBlocking(tmpBuf, false);
            }
        }
    } catch (Exception e) {
        if (buffer != null && buffer.refCnt() > 0) {
            buffer.release();
        }
        throw new IOException(e);
    }
    updateWritten(len);
}
 
Example 12
Source File: MyDynamicProtocolChannelHandler.java    From spring-boot-protocol with Apache License 2.0 5 votes vote down vote up
@Override
protected void onOutOfMaxConnection(ChannelHandlerContext ctx, ByteBuf msg, TcpChannel tcpChannel) {
    if(tcpChannel.getProtocolName().contains("http")){
        onOutOfMaxConnectionByHttp(tcpChannel);
    }else {
        ctx.close();
    }
    if(msg != null && msg.refCnt() > 0) {
        msg.release();
    }
}
 
Example 13
Source File: DefaultGatewayClient.java    From Discord4J with GNU Lesser General Public License v3.0 5 votes vote down vote up
private static void safeRelease(ByteBuf buf) {
    if (buf.refCnt() > 0) {
        try {
            buf.release();
        } catch (IllegalReferenceCountException e) {
            if (log.isDebugEnabled()) {
                log.debug("", e);
            }
        }
    }
}
 
Example 14
Source File: InboundEnvelopeDecoderTest.java    From stratosphere with Apache License 2.0 5 votes vote down vote up
@Test
public void testBufferStagingStagedBufferException() throws Exception {
	final EmbeddedChannel ch = new EmbeddedChannel(
			new OutboundEnvelopeEncoder(),
			new InboundEnvelopeDecoder(this.bufferProviderBroker));

	when(this.bufferProviderBroker.getBufferProvider(anyJobId(), anyChannelId()))
			.thenReturn(this.bufferProvider);

	// --------------------------------------------------------------------

	ByteBuf buf = encode(ch, nextEnvelope(true));

	when(this.bufferProvider.requestBuffer(anyInt()))
			.thenReturn(null);

	when(this.bufferProvider.registerBufferAvailabilityListener(Matchers.<BufferAvailabilityListener>anyObject()))
			.thenReturn(BufferAvailabilityRegistration.SUCCEEDED_REGISTERED);

	// --------------------------------------------------------------------

	int refCount = buf.refCnt();

	decodeAndVerify(ch, buf);

	Assert.assertFalse(ch.config().isAutoRead());
	Assert.assertEquals(refCount + 1, buf.refCnt());

	try {
		decodeAndVerify(ch, buf);
		Assert.fail("Expected IllegalStateException not thrown");
	} catch (IllegalStateException e) {
		// expected exception
	}

	buf.release();
}
 
Example 15
Source File: EmbeddedChannelTest.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
private static void release(ByteBuf... buffers) {
    for (ByteBuf buffer : buffers) {
        if (buffer.refCnt() > 0) {
            buffer.release();
        }
    }
}
 
Example 16
Source File: Buffers.java    From couchbase-jvm-core with Apache License 2.0 4 votes vote down vote up
@Override
public void call(ByteBuf byteBuf) {
    if (byteBuf != null && byteBuf.refCnt() > 0) {
        byteBuf.release();
    }
}
 
Example 17
Source File: DynamicProtocolChannelHandler.java    From spring-boot-protocol with Apache License 2.0 4 votes vote down vote up
protected void onOutOfMaxConnection(ChannelHandlerContext ctx, ByteBuf msg,TcpChannel tcpChannel){
    ctx.close();
    if(msg != null && msg.refCnt() > 0) {
        msg.release();
    }
}
 
Example 18
Source File: InboundEnvelopeDecoderTest.java    From stratosphere with Apache License 2.0 4 votes vote down vote up
@Test
public void testEncodeDecodeRandomEnvelopes() throws Exception {
	final InboundEnvelopeDecoder decoder = new InboundEnvelopeDecoder(this.bufferProviderBroker);
	final EmbeddedChannel ch = new EmbeddedChannel(
			new OutboundEnvelopeEncoder(), decoder);

	when(this.bufferProviderBroker.getBufferProvider(anyJobId(), anyChannelId()))
			.thenReturn(this.bufferProvider);

	when(this.bufferProvider.requestBuffer(anyInt())).thenAnswer(new Answer<Object>() {
		@Override
		public Object answer(InvocationOnMock invocation) throws Throwable {
			// fulfill the buffer request with the requested size
			return allocBuffer((Integer) invocation.getArguments()[0]);
		}
	});

	Random randomAnswerSource = new Random(RANDOM_SEED);

	RandomBufferRequestAnswer randomBufferRequestAnswer = new RandomBufferRequestAnswer(randomAnswerSource);

	RandomBufferAvailabilityRegistrationAnswer randomBufferAvailabilityRegistrationAnswer =
			new RandomBufferAvailabilityRegistrationAnswer(randomAnswerSource, randomBufferRequestAnswer);

	when(this.bufferProvider.requestBuffer(anyInt())).thenAnswer(randomBufferRequestAnswer);

	when(this.bufferProvider.registerBufferAvailabilityListener(Matchers.<BufferAvailabilityListener>anyObject()))
			.thenAnswer(randomBufferAvailabilityRegistrationAnswer);

	// --------------------------------------------------------------------

	Envelope[] envelopes = nextRandomEnvelopes(1024);

	ByteBuf buf = encode(ch, envelopes);

	ByteBuf[] slices = randomSlices(buf);

	for (ByteBuf slice : slices) {
		int refCount = slice.refCnt();
		ch.writeInbound(slice);

		// registered BufferAvailabilityListener => call bufferAvailable(buffer)
		while (randomBufferAvailabilityRegistrationAnswer.isRegistered()) {
			randomBufferAvailabilityRegistrationAnswer.unregister();

			Assert.assertFalse(ch.config().isAutoRead());
			Assert.assertEquals(refCount + 1, slice.refCnt());

			// return a buffer of max size => decoder needs to limit buffer size
			decoder.bufferAvailable(allocBuffer(MAX_BUFFER_SIZE));
			ch.runPendingTasks();
		}

		Assert.assertEquals(refCount - 1, slice.refCnt());
		Assert.assertTrue(ch.config().isAutoRead());
	}

	Envelope[] expected = randomBufferAvailabilityRegistrationAnswer.removeSkippedEnvelopes(envelopes);

	decodeAndVerify(ch, expected);

	Assert.assertEquals(1, buf.refCnt());

	buf.release();
}
 
Example 19
Source File: MuChannelHandler.java    From vethrfolnir-mu with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
	ByteBuf buff = (msg instanceof ByteBuffer) ? ctx.alloc().buffer().writeBytes((ByteBuffer)msg) : (ByteBuf)msg;

	buff.readerIndex(2);
	
	int opcode = buff.readUnsignedByte();
	switch (opcode) { // double opcode
		case 0xf1:
		case 0xf3:
		case 0x0e:
		case 0x03:
			buff.readerIndex(buff.readerIndex() - 1);
			opcode = buff.readUnsignedShort(); // ex 0xF1_03
			break;
		default:
			break;
	}
	
	if(opcode == 0xe00) { // Time packet?
		buff.clear();
		buff.release();
		return;
	}

	ReadPacket packet = clientpackets.get(opcode);
	
	if(packet != null) {
		MuClient client = ctx.channel().attr(MuClient.ClientKey).get();
		//System.out.println("Got opcode: 0x"+PrintData.fillHex(opcode, 2)+ " packet = \n"+packet.getClass().getSimpleName());
		packet.read(client, buff);
	}
	else {
		log.warn("Unknown packet[opcode = 0x"+PrintData.fillHex(opcode, 2)+"]. Dump: ");
		log.warn(PrintData.printData(buff.nioBuffer(0, buff.writerIndex())));
	}
	
	//log.warn(PrintData.printData(buff.nioBuffer(0, buff.writerIndex())));
	
	if(buff.refCnt() > 0) {
		//System.out.println("Handler Release when packet[opcode = 0x"+PrintData.fillHex(opcode, 2)+"]");
		buff.release();
	}
}
 
Example 20
Source File: VertxHttpExchange.java    From quarkus-http with Apache License 2.0 4 votes vote down vote up
@Override
public void writeBlocking0(ByteBuf data, boolean last) throws IOException {
    if (upgradeRequest && getStatusCode() != 101) {
        response.headers().add(HttpHeaderNames.CONNECTION, "close");
    }
    if (responseDone) {
        if (last && data == null) {
            return;
        }
        data.release();
        throw new IOException("Response already complete");
    }
    if (last && data == null) {
        responseDone = true;
        if (upgradeHandler == null) {
            request.response().end();
        } else {
            request.response().end(upgradeHandler);
        }
        return;
    }
    try {
        //do all this in the same lock
        synchronized (request.connection()) {
            awaitWriteable();
            try {
                if (last) {
                    responseDone = true;
                    if (upgradeHandler == null) {
                        request.response().end(createBuffer(data));
                    } else {
                        request.response().end(createBuffer(data), upgradeHandler);
                    }
                } else {
                    request.response().write(createBuffer(data));
                }
            } catch (Exception e) {
                if (data != null && data.refCnt() > 0) {
                    data.release();
                }
                throw new IOException("Failed to write", e);
            }
        }
    } finally {
        if (last) {
            terminateResponse();
        }
    }
}