Example usage for io.netty.channel.socket DatagramPacket release

List of usage examples for io.netty.channel.socket DatagramPacket release

Introduction

In this page you can find the example usage for io.netty.channel.socket DatagramPacket release.

Prototype

boolean release();

Source Link

Document

Decreases the reference count by 1 and deallocates this object if the reference count reaches at 0 .

Usage

From source file:com.mpush.netty.udp.UDPChannelHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    DatagramPacket datagramPacket = (DatagramPacket) msg;
    Packet packet = PacketDecoder.decodeFrame(datagramPacket);
    receiver.onReceive(packet, connection);
    datagramPacket.release();//??
}

From source file:com.streamsets.pipeline.lib.udp.PacketQueueUDPHandler.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket packet) throws Exception {
    packet.retain();//  w ww .jav a2s .  c o  m
    final boolean succeeded = queue.offer(packet);
    if (succeeded) {
        gaugeMap.put(GAUGE_NUM_QUEUED_PACKETS, queuedPacketCount.incrementAndGet());
        gaugeMap.put(GAUGE_PACKET_QUEUE_SIZE, queue.size());
    } else {
        gaugeMap.put(GAUGE_NUM_DROPPED_PACKETS, droppedPacketCount.incrementAndGet());
        // allow Netty to collect the buffer
        packet.release();
    }
}

From source file:com.streamsets.pipeline.stage.origin.udp.MultithreadedUDPSource.java

License:Apache License

@Override
public void produce(Map<String, String> offsets, int maxBatchSize) throws StageException {
    Utils.checkNotNull(udpServer, "UDP server is null");

    final int finalMaxBatchSize = Math.min(configs.batchSize, maxBatchSize);

    try {//from ww w .  j  a  v  a 2s .  c  o  m
        ExecutorCompletionService<Future> completionService = new ExecutorCompletionService<>(executorService);

        List<Future> allFutures = new LinkedList<>();
        IntStream.range(0, numWorkerThreads).forEach(threadNumber -> {
            Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    BatchContext batchContext = null;
                    long remainingTime = configs.maxWaitTime;
                    while (!getContext().isStopped()) {
                        if (batchContext == null) {
                            batchContext = getContext().startBatch();
                        }

                        final long startingRecordCount = recordCount;
                        try {
                            long start = System.currentTimeMillis();
                            //ParseResult result = incomingQueue.poll(remainingTime, TimeUnit.MILLISECONDS);

                            final DatagramPacket packet = handler.getPacketQueue().poll(remainingTime,
                                    TimeUnit.MILLISECONDS);
                            List<Record> records = null;
                            if (packet != null) {
                                if (LOG.isTraceEnabled()) {
                                    LOG.trace("Took packet; new size: {}", handler.getPacketQueue().size());
                                }

                                try {
                                    records = parser.parse(packet.content(), packet.recipient(),
                                            packet.sender());
                                } catch (OnRecordErrorException ex) {
                                    getContext().reportError(ex.getErrorCode(), ex.getParams());
                                } catch (Exception e) {
                                    getContext().reportError(e);
                                    continue;
                                } finally {
                                    packet.release();
                                }
                            }
                            long elapsedTime = System.currentTimeMillis() - start;
                            if (elapsedTime > 0) {
                                remainingTime -= elapsedTime;
                            }

                            if (records != null) {
                                if (IS_TRACE_ENABLED) {
                                    LOG.trace("Found {} records", records.size());
                                }
                                for (Record record : records) {
                                    if (IS_TRACE_ENABLED) {
                                        LOG.trace("Processed {} records", (recordCount - startingRecordCount));
                                    }

                                    batchContext.getBatchMaker().addRecord(record);

                                    if (++recordCount % finalMaxBatchSize == 0) {
                                        getContext().processBatch(batchContext);
                                        batchContext = getContext().startBatch();
                                    }
                                }
                            }

                            if (remainingTime <= 0) {
                                remainingTime = configs.maxWaitTime;
                                getContext().processBatch(batchContext);
                                batchContext = getContext().startBatch();
                            }
                        } catch (InterruptedException e) {
                            Thread.currentThread().interrupt();
                        }
                    }
                }
            };
            allFutures.add(completionService.submit(runnable, null));
        });

        while (!getContext().isStopped()) {
            ThreadUtil.sleep(101);
        }

        for (Future future : allFutures) {
            try {
                future.get();
            } catch (ExecutionException e) {
                LOG.error(
                        "ExecutionException when attempting to wait for all UDP runnables to complete, after context was"
                                + " stopped: {}",
                        e.getMessage(), e);
            } catch (InterruptedException e) {
                LOG.error(
                        "InterruptedException when attempting to wait for all UDP runnables to complete, after context "
                                + "was stopped: {}",
                        e.getMessage(), e);
                Thread.currentThread().interrupt();
            }
        }
    } finally {
        if (!executorService.isShutdown()) {
            executorService.shutdown();
        }
    }

}

From source file:me.melchor9000.net.UDPSocket.java

License:Open Source License

public Packet receiveFrom(ByteBuf data, int bytes) throws Throwable {
    checkSocketCreated("receiveFrom");
    if (canReadDirectly) {
        if (receivedPackets.peek().content().readableBytes() > bytes)
            throw new NotEnoughSpaceForPacketException("Cannot write the message into the ByteBuf",
                    receivedPackets.peek().content().readableBytes(), receivedPackets.peek().sender());
        DatagramPacket packet = receivedPackets.poll();
        int bytes2 = packet.content().writableBytes();
        packet.content().writeBytes(data, packet.content().writableBytes());
        canReadDirectly = false;//from w ww  . j  a  va  2  s .co m
        packet.release();
        return new Packet(data, packet.sender(), bytes2);
    } else {
        return receiveAsyncFrom(data, bytes).sync().getValueNow();
    }
}