netty-AbstractReferenceCounted用法测试例子

Netty资源泄露检测ResourceLeakDetector 资源泄露  ByteBuf不再使用后(没有引用),没有调用release,导致ByteBuf资源一直被占用无法回收。检测原理原理:每次创建ByteBuf时,创建一个虚引用对象A指向该ByteBuf对象,如果正常调用release()操作,则虚引用对象A和ByteBuf对象均被回收;如果ByteBuf对象不再使用(没有其他引用)但没有调用release()操作,则GC时虚引用对象A被加入Referen 阅读详情

import io.netty.util.AbstractReferenceCounted;
import io.netty.util.ReferenceCounted;
import io.netty.util.ResourceLeakDetector;
import io.netty.util.ResourceLeakTracker;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by lihong10 on 2017/6/16.
 */
public class ReferenceAbleObj extends AbstractReferenceCounted {

    private static ResourceLeakDetector<ReferenceAbleObj> detector =
            new ResourceLeakDetector(ReferenceAbleObj.class, 2);
    ResourceLeakTracker<ReferenceAbleObj> track = null;

    public ReferenceAbleObj(){
        super();
        this.track = detector.track(this);

    }

    //release()调用后,如果refCnt为0, 会执行该方法
    protected void deallocate() {
        System.out.println("开始回收对象自身, 此时的引用数是:" + refCnt());
        if (refCnt() == 0) {
            System.out.println(track);
            track.close(this); //不再追踪
        }
        track = null;
        System.out.println("回收结束");
    }

    @Override
    public ReferenceCounted touch(Object hint) {
        if (track != null) {
            track.record(hint);
        }
        return this;
    }

    public void action1() {
        touch("再次被使用");
    }

    public void action2() {
        touch("再次被使用");
    }


    public static void main(String... args) {


        detector.setLevel(ResourceLeakDetector.Level.PARANOID);
        ReferenceAbleObj obj = new ReferenceAbleObj();
        System.out.println("初始引用数:" + obj.refCnt());
        obj.retain();
        System.out.println("retain后的引用数:" +  obj.refCnt());


        obj.touch("第1次被使用");
        obj.touch("第2次被使用");

        obj.action1();
        obj.action2();



        AtomicInteger i = new AtomicInteger(0);
        boolean release1 = obj.release();
        System.out.println("第" + i.addAndGet(1) + "次释放:" + release1 +  " " + obj.refCnt());

        System.out.println("第" + i.addAndGet(1) + "次释放即将开始");
        obj.release();

    }




}





【netty】netty ResourceLeakDetector 资源泄露检测 当你通过 ChannelInboundHandler.channelRead(…) 或者 ChannelOutboundHandler.write(…) 来处理数据,重要的是在处理资源时要确保资源不要泄漏。Netty 使用引用计数器来处理池化的 ByteBuf。所以当 ByteBuf 完全处理后,要确保引用计数器被调整。引用计数的权衡之一是用户时必须小心使用消息。当 JVM 仍在 GC(不知道有这样的消息引用计数)这个消息,以至于可能是之前获得的这个消息不会被放回池中。 阅读详情

相关推荐

Ferry工单平台部署

ferry工单平台部署

运维求生之路 1897

Netty的资源泄露探测器:ResourceLeakDetector

因为 Netty 大量使用 ByteBuf,如果 ByteBuf出现泄露,则服务很容易出现 OOM。Netty 中的ResourceLeakDetector就是为解决该问题而生,它记录 Netty 使用的各种 ByteBuf的使用,能对占用资源的对象进行监控。无论是 Pooled 还是 Unpooled,无论是 Direct 还是 Heap,所有的 ByteBuf都要被 ResourceLe...

布道 7952

数据库崩溃恢复机制:REDO日志与UNDO日志详解

在数据库管理系统中,事务的持久性和一致性是至关重要的。为了保证在系统崩溃或发生故障时数据不会丢失,数据库引入了恢复机制。其中,REDO日志和UNDO日志是两种关键的恢复技术。本文将详细描述这两种日志的作用、工作原理以及它们在数据库崩溃恢复中的应用。

My_wife_QBL的博客 1413

AbstractReferenceCountedByteBuf笔记

类定义 public abstract class AbstractReferenceCountedByteBuf extends AbstractByteBuf {} public abstract class AbstractByteBuf extends ByteBuf {} public abstract class ByteBuf implements ReferenceCounted, Comparable<ByteBuf> {} ByteBuf申明了对接口ReferenceCou

编程牧马人 464

新手必看:5分钟搞定Unitree Go1机器狗Gazebo仿真运动控制(附按键图解)

本文为新手提供了Unitree Go1机器狗在Gazebo仿真环境中实现运动控制的快速指南。通过5分钟极简配置和按键图解,帮助开发者快速掌握宇树科技明星产品的基础操作,包括环境搭建、仿真启动和运动控制技巧,适合零基础用户快速上手。

weixin_42550597的博客 300

Replay音频转换时samplerate缺失的解决方案指南

Replay音频转换时提示"No module named 'samplerate' This error is lazily reported, having originally occured in File"的解决方案

weixin_47445543的博客 2136

鸿蒙5.0版开发:分析Resource Leak(资源泄漏)

本文将分别介绍资源泄漏检测能力、泄漏问题定位分析思路,以及具体的案例分析。

m0_73088370的博客 1993

安装升级最新版本postman时遇到“无法定位程序输入点 SetDefaultDllDirectories于动态链接库KERNEL32.dll 上.”的问题

软件版本迭代更新真快,最近升级最新Postman版本时出现以下问题 我就简单纪录下解决办法: 备注:我用的是最新的postman工具包:Postman-win64-7.25.0-Setup.exe,目前是最新 0. 前提是已经到postman官网https://www.postman.com/downloads/下载好软件工具包 1.安装window7系统更新补丁KB2533623,请到微软公司官网https://support.microsoft.com/en-us/help/2...

董广明的博客 1万+

14-ReferenceCounted

文章目录ReferenceCounted一、接口定义1.1 注释1.2 方法二、ReferenceCounted的实现2.1 ByteBuf2.2 AbstractReferenceCountedByteBuf2.2.1 AtomicIntegerFieldUpdater2.2.2 deallocate方法三、deallocate的实现3.1 PooledByteBuf3.2 Unpooled...

my_momo_csdn的博客 837

ImportError: DLL load failed while importing _pydantic_core: 找不到指定的程序对应解决方案

本文主要介绍了ImportError: DLL load failed while importing _pydantic_core: 找不到指定的程序对应解决方案,希望能对使用Python的同学们有所帮助。 文章目录 1. 问题描述 2. 解决方案

weixin_43178406的博客 19万+

Windows原生环境配置Tensorflow使用GPU

本文讲解如何在Windows原生环境搭建可调用GPU设备进行计算的Tensorflow2.x环境。 区别于WSL,使用Windows原始环境作为开发环境。

天然玩家的博客 1501

netty使用ResourceLeakDetector检测内存泄漏问题

文章目录相关参数检测级别:junit5+embeddedchannel 检测handler内存泄漏问题 相关参数 -Dio.netty.noResourceLeakDetection=false # 就版本是否禁用泄漏检测, 默认不禁用, 已过时, 新版本建议用检测级别配置设置 -Dio.netty.leakDetectionLevel=PARANOID #旧版本配置, paranoid级别检测 -Dio.netty.leakDetection.level=advanced #新版本配置, advanc

编程随手记 3144

pg lib的信息及产生pg lib的三种方法

pg lib相比basic lib会多几方面pg 信息。除了pg arc(pg pin)以外,liberty还提供电压值,以及pmk cell的power_down_function功能相关信息。1.电压值除了常见的primary pg还有secondary pg和衬底。2.pg arc后端需要去做redhawk功耗分析,需要pg liberty提供pg arc,如果没有pg arc就需要手动去写custom lib代替3.pmk cell的power_down_function。

m0_61544122的博客 595

netty AbstractReferenceCountedByteBuf类

AbstractReferenceCountedByteBuf 作用 AbstractReferenceCountedByteBuf类提供了引用计数的功能,其所有的子类都可以使用该功能防止内存泄漏。 属性 REFCNT_FIELD_OFFSET:refCnt字段在内存中的地址偏移量 AIF_UPDATER:refCnt字段更新器 updater:更新器 refCnt:保存引用计数的字段 priva...

我是兴锅的博客 701

OV9734 DATASHEET,完整规格书

OV9734完整规格书,包括电气参数,尺寸规格,寄存器配置表等

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

netty源码分析之-ReferenceCounted详解(9)

被引用计数包含的对象,能够显示的被垃圾回收。当初始化的时候,计数为1。retain()方法能够增加计数,release() 方法能够减少计数,如果计数被减少到0则对象会被显示回收,再次访问被回收的这些对象将会抛出异常。如果一个对象实现了ReferenceCounted,并且包含有其他对象也实现来ReferenceCounted,当这个对象计数为0被回收的时候,所包含的对象同样会通过release(

huiGod的博客 2729

假人有限元模型

假人模型,车辆碰撞假人有限元模型,适合做乘员安全的研究者利用

netty-ResourceLeakDetector用法测试

在netty中,只要实现了ReferenceCounted 这个接口的类,都需要保证在正确的时刻调用"release"方法,否则这个对象的引用计数无法被重置为0。最终后果是这个被使用过的对象无法返回对象池或无法释放其内部占用的内存,从而导致内存泄漏。 netty中, 即便是老手,也经常会因为对引用计数对象的不当使用导致内存泄漏,幸运的是netty也提供了检测内存泄漏的工具类ResourceLeak...

lhever_的博客 4395

io.netty.util.ReferenceCounted 是什么

io.netty.util.ReferenceCounted 是 Netty 中的一个接口,它提供了一种引用计数机制,用于管理内存的生命周期。在 Netty 中,很多对象(例如 ByteBuf)都实现了 ReferenceCounted 接口,以便在使用完对象时能够自动释放资源,避免内存泄漏。

weixin_44594317的博客 906

《Netty in Action》中文版—第六章 ChannelHandler和ChannelPipeline

本章包含 ChannelHandler和ChannelPipeline APIs检测资源泄露异常处理 在前一章,你学习了Netty的数据容器ByteBuf。在这一章我们会在你已经学过的知识的基础上探讨Netty的数据流和处理模块。你会开始看到这个框架的一些重要元素被组合到一起了。 你已经了解到,ChannelHandler在一个ChannelPipeline中被链在一起,将所有的

fishmai的专栏 1万+

Netty中引用计数实现原理详解:ReferenceCounted, AbstractReferenceCountedByteBuf, ReferenceCountUpdater

是ByteBuf的一个抽象子类,它实现了接口,为ByteBuf的引用计数提供了具体的实现框架。这个类通过维护一个引用计数字段来跟踪ByteBuf的引用状态,并提供了对接口方法的默认实现。Netty通过接口、抽象类以及工具类实现了高效的引用计数机制。这一机制确保了ByteBuf等资源在不再被需要时能够被及时释放,从而避免了内存泄漏问题。开发者在使用Netty进行网络编程时,应当注意合理调用retain()和release()方法,以确保引用计数的正确性。

码到三十五 1471

Netty核心接口源码之ReferenceCounted

位于 netty 自己的工具包下 一个引用计数的对象,需要显式取消分配。 当实例化一个新的ReferenceCounted时,它从引用计数1开始。 retain 引用计数加一 release引用计数减一。如果引用计数减到0,则将显式释放对象,并且访问该释放对象通常会导致访问冲突。 如果实现ReferenceCounted的对象是其他实现ReferenceCounted的对象的容器,则当容器的引用计数变为0时,包含的对象也将通过release释放。 API int refCnt() 返回.

JavaEdge全是干货的技术号 1723

解决java.lang.NoClassDefFoundError错误

解决Java报错:java.lang.NoClassDefFoundError错误

努力才是唯一的入场券。 12万+

stream銆俠oxed_netty io.netty.buffer简介

io.netty.util.ReferenceCounted此接口代表一个引用计数的对象,此对象需要显示的释放.当一个方法会减少引用数量,如果引用数量减少到0,该对象就需要显示释放掉。访问释放掉的对象通常会导致访问冲突。如果实现主要方法:intrefCnt();//返回当前对象的引用数量,如果返回零,说明当前对象已经被释放掉了ReferenceCountedretain();//引用数量增加...

weixin_39617252的博客 277

从NIO到netty(14) ByteBuf和ReferenceCounted

ByteBuf是Netty提供的代替jdk的ByteBuffer的一个容器,首先看一下他的具体用法: public class ByteBufTest0 { public static void main(String[] args) { ByteBuf byteBuf = Unpooled.buffer(10);//堆缓冲区 for(int i=0;i&...

m0_37139189的博客 385

Netty之引用计数

Netty中实现引用计数的接口是ReferenceCounted,一个实现了ReferenceCounted接口的类就具备了引用计数的能力。 当一个引用计数的对象被初始化时, 引用计数器被初始化为1。 ReferenceCounted接口中两个主要的方法: retain()方法对引用计数加1,release()方法对引用计数减1。如果引用计数被减到0...

猎户星座 1237

Netty是如何检测资源泄漏的?

为了减轻GC的压力、以及避免频繁向OS申请和释放内存,Netty基于JeMalloc思想自己实现了一套内存管理方案。不管是堆内存还是直接内存,都可以交给Netty来统一管理,这带来了两个好处,一是可以减轻GC的压力,二是可以避免向OS频繁申请和释放内存,Netty一次性申请一大块内存,然后按需分配。 同时,也带来一个坏处,就是开发者使用完毕后,必须及时释放掉资源,否则会导致内存泄漏。 综上所述,自己管理内存会带来更好的性能,但是也增大了内存泄漏的可能性。为了尽量避免内存泄漏,Netty提供了Resource

程序员小潘 1354

Netty 源码剖析:ByteBuf 内存泄漏的产生原因与 ResourceLeakDetector 检测原理

本篇文章基于 Netty 4.1.6 源码,从「为什么池化 ByteBuf 会泄漏内存」与「Netty 如何自动检测泄漏」两个核心问题出发,深入剖析 ByteBuf 的引用计数(refCnt)机制、`release0()` 与 `deallocate()` 的完整释放链路,以及 Netty 内存泄漏检测器(ResourceLeakDetector)借助虚引用(PhantomReference)与

gitblog_00400的博客 438
上一篇: 为什么要进行内存对齐以及对齐规则
下一篇: netty - ThreadDeathWatcher用法测试
lhever_
博客等级 码龄14年 213粉丝 130原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值