Tomcat源码分析之:ServletOutputStream的实现

【Jsp】第三课 Servlet常用对象(三) 在Servlet技术的学习过程中,需要用到很多的常用对象,而且其用法也非常重要,这里介绍第二个常用对象,HttpServletResponse 概述 1. Servlet收到浏览器的http请求后,会针对每一次请求,分别创建一个用于代表请求的request对象、和代表响应的response对象 2. request和response对象即代表了请求和响应,那我们要获取浏览器提交过来的数据,只需要找request对象就可以了,Servlet要想将数据发送给浏览器上显示,只需要找response即可 阅读详情

貌似很久都没有写博客了,tomcat8的代码已经看了很多,主体部分的代码也都看得差不多了,发现在tomcat8中已经完全支持非阻塞的方式接收以及发送数据了。。。。但是比较遗憾的是,以前遗留下来的太多的老代码都不支持这种新的方式来发送数据。。。木有办法。。。

这里来看看Tomcat中是如何实现ServletOutputStream的吧。。。。

在具体的来看它之前,这里先来一张图来描述一下Tomcat的数据发送时候的流动。。。



这张图形已经比较好的展现成了Tomcat中对IO这一块封装的层次关系吧,首先是最上层的

ServletOutputStream对象,它是用户代码可以接触到的对象,它自带了自己的OutputBuffer,这里写数据其实是通过这个这个buffer完成的,数据是写到这个OutputBuffer里面

接下来的一层就是Tomcat内部的Response类型了,每一个ServletResponse对象都对应着一个唯一的Tomcat内部的response类型,当然了,他也有自己的buffer,InternalNioOutputBuffer类型的对象,这里上层ServletOutputStream写数据将会流动到这里。。。

最下层就是与channel关联的部分了,它也有自己的buffer,这里一般就是java类库中的niobuffer,上层的数据将会流动到这里。。。

最后才是将数据通过channel发送出去。。。

嗯,虽然好像层次稍微多了些,而且刚刚开始看代码就觉得稍微有点繁琐。。不过当将这个层次关系理清楚了之后还是蛮简单的。。。

好啦,接下来来看代码了。。。

这里就通过一次write来跟踪整个代码的执行轨迹吧,首先来看看CoyoteOutputStream类型的write方法:

    //发送一个byte数组的一部分数据
    public void write(byte[] b, int off, int len) throws IOException {
        boolean nonBlocking = checkNonBlockingWrite();  //判断是否支持非阻塞的发送数据,这里判断的标准其实是用户代码是否加入了WriteListener
        ob.write(b, off, len);  //将数据写到outputbuffer里面
        if (nonBlocking) {
            checkRegisterForWrite();  //如果是非阻塞的发送数据的话,需要确保channel有注册写事件
        }
    }

这里首先要判断是否支持非阻塞的发送数据,这里就不细讲这部分的类容了,,,来看看这里的outputbuffer的write行为吧:

//写入一个字节数组的一部分
    public void write(byte b[], int off, int len) throws IOException {

        if (suspended) {
            return;
        }

        writeBytes(b, off, len);

    }


    private void writeBytes(byte b[], int off, int len)
        throws IOException {

        if (closed) {  //如果已经关闭了,那么直接返回吧
            return;
        }
        //这里其实是写到buffer里,如果数据过大,也有可能调用realWriteBytes方法真正的调用底层写数据
        bb.append(b, off, len);
        bytesWritten += len;

        // if called from within flush(), then immediately flush
        // remaining bytes
        if (doFlush) {
            bb.flushBuffer();
        }

    }

这里其实就是将数据直接放到当年的bytechunk就好了。。。但是这里如果数据比较多的话,会将数据直接写到下一层,也就是tomcat内置的response。。。来看看bytechunk的append方法吧:

    //加入一个字节数组的一部分数据
    public void append( byte src[], int off, int len )
    
FPGA实战:手把手教你用Verilog实现Modbus CRC16校验(附完整代码) 本文详细介绍了在FPGA中实现Modbus RTU协议CRC16校验模块的完整实战方案。针对硬件设计中的时序、资源与性能挑战,文章从算法原理出发,提供了清晰的Verilog模块接口、状态机设计、查表ROM实现及优化策略,并附带了完整的可综合代码与测试平台,帮助工程师高效构建稳定可靠的工业通信系统。 阅读详情

相关推荐

蓝牙开发实战:如何用Wireshark抓取HCI协议包(附完整分析步骤)

本文详细介绍了如何使用Wireshark抓取和分析蓝牙HCI协议包,包括环境搭建、过滤器配置技巧、数据包深度解析及高级调试方法。通过实战案例,帮助开发者快速定位蓝牙连接问题,提升调试效率。

cuda7parallel的博客 1147

【maxENT】从数据到地图:R语言实现最大熵物种分布建模全流程解析

本文详细解析了如何使用R语言实现最大熵模型(MaxEnt)进行物种分布建模的全流程。从数据准备、环境变量处理到模型训练与参数调优,再到模型评估与结果可视化,提供了实用的代码示例和避坑指南。特别适合生态学研究者利用最大熵模型处理物种分布数据,提升研究效率。

weixin_27244795的博客 214

当传统CFD遇上AI:PINN如何帮我们省下90%的仿真计算时间?

本文探讨了物理信息神经网络(PINN)在计算流体力学(CFD)中的应用,如何通过无网格方法节省90%的仿真计算时间。PINN将物理定律编码到神经网络中,显著减少传统CFD中的网格生成和计算时间,同时保持高精度。文章还对比了PINN与传统方法的性能,并讨论了其独特优势和当前局限。

weixin_32678995的博客 319

YOLOv12 改进 | Backbone改进 3

将CSP中的简单拼接改为可学习的特征选择门控,动态决定哪些特征流向下一层,同样再写这篇。:相比静态CSP的固定50/50分割,门控机制可学习0.3:0.7等最优比例。在输入端加入轻量SR模块,对下采样后的特征进行超分恢复,提升小目标检测能力。(小目标): 从 0.51 AP → 0.63 AP (+24%):采用ESPCN的高效亚像素卷积,避免传统插值的信息损失。:从通道级(SE)到空间级(Spatial)的多粒度控制。:结合浅层细节和深层语义,恢复小目标的纹理信息。

u012133341的博客 839

【异常】出现“‘git‘ 不是内部或外部命令,也不是可运行的程序”的错误

出现“‘git’ 不是内部或外部命令,也不是可运行的程序”的错误通常意味着 Git 没有被正确安装在你的系统上,或者其可执行文件的路径没有被添加到系统的环境变量中。

奶爸的编程之路,也就一周冷个三天 1388

MuJoCo Playground 机器人强化学习入门教程(一)

MuJoCo Playground 包含 DM 控制套件、机器人运动和机器人操作环境。env每个环境还与一个环境配置相关联,如果需要,可以覆盖该配置。env_cfg请注意,环境配置包含 sim_dt 和 ctrl_dt。ctrl_dt 决定每个 env.step 的时间间隔。因此,每个 env.step 的模拟步长为 ctrl_dt / sim_dt 倍。其他值得注意的参数还有 vision_config,我们将在基于视觉的笔记本中详细讨论!现在,我们将专注于特权观察。

2506_90492529的博客 4614

fanuc机器人KAREL中 函数的应用

本次课程讲解编程的思路。很多的同学都玩过积木,一个一个的模块逐渐累积起来,通过彼此之间的相互联系,最终形成一个完整的整体。其实编程也是这样。 将一个对象根据其特点进行模块化拆分,尤其是一些特点非常相似的内容,将其变成一个模块。然后通过传递参数,实现不同的功能,这就是模块化编程。

haier123888的博客 2743

Autosar MCAL-S32K324 Fee配置-基于EB

Autosar MCAL S32K324 Fee配置详解

赞的博客 1544

Data-Structures-and-Algorithm-Analysis-in-Java.pdf

作者: Weiss, Mark A. 出版社: Addison Wesley Data Structures and Algorithm Analysis in Java is an “advanced algorithms” book that fits between traditional CS2 and Algorithms Analysis courses. In the old ACM Curriculum Guidelines, this course was known as CS7. This text is for readers who want to learn good programming and algorithm analysis skills simultaneously so that they can develop such programs with the maximum amo...

锂电池充电器电路设计 里面有电路

锂电池充电器电路设计 里面有电路 3.7V升压到5V电路设计。

WINCC7.3破解文件

WINCC7.3硬件够破解文件,有需要的下载!WINCC7.3硬件够破解文件,有需要的下载!

深度学习工具包 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")

上一篇: java类库concurrent中最核心类型AbstractQueuedSynchronizer的学习
下一篇: linux下实现监控进程网络带宽
fjs_cloud
博客等级 码龄15年 248粉丝 192原创
评论 2
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值