| 注册
请输入搜索内容

热门搜索

Java Linux MySQL PHP JavaScript Hibernate jQuery Nginx

servlet与Struts,action线程分析

0
Java HTML C/C++ Go Servlet 13500 次浏览

Servlet/JSP技术和ASPPHP等 相比,由于其多线程运行而具有很高的执行效率。由于Servlet/JSP默认是以多线程模式执行 的,所以,在编写代码时需要非常细致地考虑多线程的安全性问题。然而,很多人编写Servlet/JSP程 序时并没有注意到多线程安全性的问题,这往往造成编写的程序在少量用户访问时没有任何问题,而在并发用户上升到一定值时,就会经常出现一些莫明其妙的问 题。

  Servlet的 多线程机制
 
   Servlet体系结构是建立在Java多 线程机制之上的,它的生命周期是由Web容器负责的。当客户端第一次请求某个Servlet时,Servlet容器将会根据web.xml配置文件实例化这个Servlet类。 当有新的客户端请求该Servlet时,一般不会再实例化该Servlet类, 也就是有多个线程在使用这个实例。Servlet容器会自动使用线程池等技术来支持系统的运行,如 图1所示。


1 Servlet线程池


   这样,当两个或多个线程同时访问同一个Servlet时,可能会发生多个线程同时访问同一资源的 情况,数据可能会变得不一致。所以在用Servlet构建的Web应 用时如果不注意线程安全的问题,会使所写的Servlet程序有难以发现的错误。

  Servlet的 线程安全问题

   Servlet的线程安全问题主要是由于实例变量使用不当而引起的,这里以一个现实的例子来说 明。

Import javax.servlet. *;
Import javax.servlet.http. *;
Import java.io. *;
Public class Concurrent Test extends HttpServlet {PrintWriter output;
Public void service (HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {String username;
Response.setContentType ("text/html; charset=gb2312");
Username = request.getParameter ("username");
Output = response.getWriter ();
Try {Thread. sleep (5000); //
为了突出并发 问题,在这设置一个延时
} Catch (Interrupted Exception e){}
output.println("
用 户名:"+Username+"
");
}
}


   该Servlet中定义了一个实例变量output, 在service方法将其赋值为用户的输出。当一个用户访问该Servlet时,程序会正常的运行,但当多个用户并发访问时,就可能会出现其它用户的信息显示在另外一些用户 的浏览器上的问题。这是一个严重的问题。为了突出并发问题,便于测试、观察,我们在回显用户信息时执行了一个延时的操作。假设已在web.xml配置文件中注册了该Servlet,现有 两个用户ab同时访问该Servlet(可以启动两个IE浏览器,或者在两台机 器上同时访问),即同时在浏览器中输入:

   ahttp://localhost: 8080/servlet/ConcurrentTest? Username=a

  bhttp://localhost: 8080/servlet/ConcurrentTest? Username=b

  如果用户b比用户a回车的时间稍慢一点,将得到如图2所示的输出:


2 a用户和b用户的浏览器输出


   从图2中可以看到,Web服务器启动了两 个线程分别处理来自用户a和用户b的请求, 但是在用户a的浏览器上却得到一个空白的屏幕,用户a的 信息显示在用户b的浏览器上。该Servlet存 在线程不安全问题。下面我们就从分析该实例的内存模型入手,观察不同时刻实例变量output的值来分析使该Servlet线程不安全的 原因。

  Java的内存 模型JMMJava Memory ModelJMM主要是为了规定了线程和内存之间的一些关系。根据JMM的 设计,系统存在一个主内存(Main Memory)Java中 所有实例变量都储存在主存中,对于所有线程都是共享的。每条线程都有自己的工作内存(Working Memory),工作内存由缓存和堆栈两部分组成,缓存中保存的是主存中变量的拷贝,缓存可能并不总和主存同步,也就是缓存中变量的修改可 能没有立刻写到主存中;堆栈中保存的是线程的局部变量,线程之间无法相互直接访问堆栈中的变量。根据JMM, 我们可以将论文中所讨论的Servlet实例的内存模型抽象为图3所示的模型。


3 Servlet实例的JMM模型


   下面根据图3所示的内存模型,来分析当用户ab的线程(简称为a线程、b线程)并发执行时,Servlet实例中所涉及变量的 变化情况及线程的执行情况,如图4所示。

调度时刻

a线程

b线程

T1

访问Servlet页面

 

T2

 

访问Servlet页面

T3

output=a的输出username=a休眠5000毫 秒,让出CPU

 

T4

 

output=b的输出(写回主存)username=b休眠5000毫 秒,让出CPU

T5

在用户b的浏览器上输出a线程的username的值,a线程终止。

 

T6

 

在用户b的浏览器上输出b线程的username的值,b线程终止。

                   图4 Servlet实例的线程调度情况

   从图4中可以清楚的看到,由于b线程对实 例变量output的修改覆盖了a线程对实 例变量output的修改,从而导致了用户a的 信息显示在了用户b的浏览器上。如果在a线 程执行输出语句时,b线程对output的 修改还没有刷新到主存,那么将不会出现图2所示的输出结果,因此这只是一种偶然现象,但这更增加了 程序潜在的危险性。
设计线程安全的Servlet

  通过上面的分析,我们知道了实例变量不正确的使用是造成Servlet线程不安全的主要原因。下面针对该问题给出了三种解决方案并对方案的选取给出了一些参考性的建 议。

  1、实现 SingleThreadModel 接口

   该接口指定了系统如何处理对同一个Servlet的调用。如果一个Servlet被这个接口指定,那么在这个Servlet中的service方法将不会有两个线程 被同时执行,当然也就不存在线程安全的问题。这种方法只要将前面的Concurrent Test类 的类头定义更改为:

Public class Concurrent Test extends HttpServlet implements SingleThreadModel {
…………
}


   2、同步对共享数据的操作

   使用synchronized 关键字能保证一次只有一个线程可以访问被保护的区段,在本论文中 的Servlet可以通过同步块操作来保证线程的安全。同步后的代码如下:

…………
Public class Concurrent Test extends HttpServlet {
…………
Username = request.getParameter ("username");
Synchronized (this){
Output = response.getWriter ();
Try {
Thread. Sleep (5000);
} Catch (Interrupted Exception e){}
output.println("
用户名:"+Username+"
");
}
}
}


   3、避免使用实例变量

   本实例中的线程安全问题是由实例变量造成的,只要在Servlet里面的任何方法里面都不使用实 例变量,那么该Servlet就是线程安全的。

   修正上面的Servlet代码,将实例变量改为局部变量实现同样的功能,代码如下:

……
Public class Concurrent Test extends HttpServlet {public void service (HttpServletRequest request, HttpServletResponse
Response) throws ServletException, IOException {
Print Writer output;
String username;
Response.setContentType ("text/html; charset=gb2312");
……
}
}


  对上面的三种方法进行测试,可以表明用它们都能设计出线程 安全的Servlet程序。但是,如果一个Servlet实 现了SingleThreadModel接口,Servlet引 擎将为每个新的请求创建一个单独的Servlet实例,这将引起大量的系统开销。SingleThreadModelServlet2.4中 已不再提倡使用;同样如果在程序中使用同步来保护要使用的共享的数据,也会使系统的性能大大下降。这是因为被同步的代码块在同一时刻只能有一个线程执行 它,使得其同时处理客户请求的吞吐量降低,而且很多客户处于阻塞状态。另外为保证主存内容和线程的工作内存中的数据的一致性,要频繁地刷新缓存,这也会大大地影响系统的性能。所以在实际的开发中也应避免或最小化 Servlet 中的同步代码;在Serlet中避免使用实例变量是保证Servlet线程安全的最佳选择。从Java 内存 模型也可以知道,方法中的临时变量是在栈上分配空间,而且每个线程都有自己私有的栈空间,所以它们不会影响线程的安全。

  小结

   Servlet的线程安全问题只有在大量的并发访问时才会显现出来,并且很难发现,因此在编写Servlet程序时要特别注意。线程安全问题主要是由实例变量造成的,因 此在Servlet中应避免使用实例变量。如果应用程序设计无法避免使用实例变量,那么使用同步来 保护要使用的实例变量,但为保证系统的最佳性能,应该同步可用性最小的代码路径。因为StrutsAction被设计为线程不安全的,所以也涉及到这个问题,所以也使用同样的方法来解决!

 

49个答案

0

This is something unique and outstanding to read and get knowledge about the main issue, The Content selection regarding the topic is up to the mark. organization 13 coat

0

Howley Carpet Providing carpet cleaner cork service with professional and reliable Prices cleaning services to domestic and commercial customers in Fermoy, Co Cork, Please visit our website for more details, Thank You.

0

Extraordinary things you've generally imparted to us. Simply continue written work this sort of posts.The time which was squandered in going for educational cost now it can be utilized for studies.Thanks http://18.180.220.14/

0

Sign up and get 10% Off, BuffK 9® Dog Supplements specialize in natural vitamins and supplements for ALL dogs! Improved lean muscle, endurance, joint health and overall well being! Visit this website for natural & Best Dog Supplements & Vitamins. At BuffK-9® Dog Supplements we specialize in healthy, 100% safe, 100% natural, side-effect free supplements for ALL family dogs. website

0

Slots sites are the most popular search online, that is why we try to collect the Best Slots Sites ​here as a list for convenience over time.

0

Please vist this Website ​to get information about natural healthy recipes, health, wellness, environment, circular economy. I tried to create something different than putting hundreds of recipes into a pot. Each recipe has a few things going for it, I try to give scientific, nutritional and more information. Because I believe that sustainability and circular economy starts and ends from what we eat, and what we eat is infinitely important for our health.

0

ReelEmperor: Play Online Casino For Real Money In India. Competet against others and win every 4 hours. Get massive rewards every time you level up, Earn points for every spin and exchange them for bonuses and much more, Please visit this site ​and sign up today to get welcome package for your first 3 deposits. Thank You this site

0

Nouveau is committed to bringing high Quality tailor-made genuine & premium faux & genuine leather backpacks for women, leather handbags & purses for women, leather shoulder bags & purses for women all over the world you can Buy Women Handbags ​from our Website ​. Every bag is shipped direct in a dust bag for protective storage. And we are currently including a Free branded Nouveau drawstring shopping backpack with every purchase. Grab one for yourself and as incredible gifts for the fashionistas in your life.

0

Smartwatch for Men and Smartwatch for Women | Benelli - Which smartwatch immediately catches your eye? Visit our Site ​for more information about the smartwatches. Before you know it, you'll be wearing this piece of special technology on your wrist. You will find best quality of smartwatches.

0

Hi, We provide a stone library and granular project management digital dry layout ​DDL is an all in one toolbox for stone blendings, offers and estimates. Please visit our website for more details. Thank You.

0

Best New Bingo Sites 2021 A2Z Sister Site Free slots no deposit No deposite casino ​| The Best Place To Find Casinos & their Sister Sites. We are one of the top largest UK online casino index sites, we have enclosed more than 2100 online casino brands their operating companies on our site. Please visit our website for more information and limited offers. Thank You.

0

We proudly serve the towns and cities located in the GTA west areas mainly Mississauga, Brampton, Milton, Oakville & Etobicoke, etc. Our fleet of tow trucks is readily available to accommodate any quick pickups for scrap cars in the above areas. junk cars for cash

0

Custom Printed Posters A4 A3 A2 A1 A0 | Digital Printing Online, Our custom printed posters are larger than life! Choose A1 Poster Printing, A2 Poster Printing, A0 Poster Printing size printed posters to advertise an event, promote business, or display a safety notice. Need help? Call our friendly support team at (01908) 696999 Or, Please visit our website for more details. A2 Poster Printing

0

Natural Mulberry Silk Eye mask for sleep - Dark Green with Travel Satchel, Wake up feeling reinvigorated, refreshed and rested.

0

Particular interviews furnish firsthand message on mart size, industry trends, ontogeny trends, capitalist landscape and outlook, etc. Supreme Saunas

0

INSTANT CASH FOR YOUR SCRAP CAR REMOVAL BRAMPTON :scrap car brampton – Sell Your Junk Cars & Get Instant Cash for Cars. If you live in the Brampton Ontario areas and are looking for scrap car removal in Brampton, Top Cash scrap car removal offers the Brampton scrap car removal service with the best & instant prices for your old Clunkers. Contact us now or get a quote & get an instant offer & the highest value cash on the spot.

0

You’ll need to hire the right IT solutions provider for your business. Read on to discover what you should look for when selecting a service provider. IT Solutions Provider

0

DOG TRAINING AND GREAT CANINE GEAR For dogs of all sizes, from Siberian Huskies to Goldendoodle’s. We have How-To guides, Grooming Tips from Groomers, Product Reviews of essentials for your pup and more for you to show how much you love your furry friend. Barkforce

0

used Louis Vuitton, Chanel preowned, Gucci, Goyard, Celine, YSL, Hermes, Preowned Luxury, Burberry, Chloe, Fendi, Luxury Handbags for less, Bottega Veneta, Jimmy Choo, MCM, Prada, Valentina, Versace, Yves Saint Laurent, Louis vuitton neverfull, louis vuitton used, louis vuitton preowned, Neverfull, Used handbags up town handbags

0

I appreciate several from the Information which has been composed, and especially the remarks posted I will visit once more. eye doctor Tulsa

1 2 3