---
title: "jsp自定义标签 线程安全"
author: "xuxujing"
date: "2014-03-05T16:46:34Z"
tags: []
categories: ["行业应用"]
slug: "jsp"
draft: false
lastmod: "2014-03-05T16:46:34Z"
id: 2026215
url: "https://xujava.iteye.com/blog/2026215"
---

转自：[http://klcwt.iteye.com/blog/749652](http://klcwt.iteye.com/blog/749652)

 

我们在编写自定义标签的时候设置属性如下

Java代码  [![收藏代码](http://klcwt.iteye.com/images/icon_star.png)]()

1. public class InputTag extends TagSupport {
2. private static final long serialVersionUID = 1L;
3. private String onclick;
4. private String style;
5. private String styleClass;
6. private String value;
7. private String id;

 

在页面上如果同时使用两个标签：

Html代码  [![收藏代码](http://klcwt.iteye.com/images/icon_star.png)]()

1. &lt;h3:input type="button" onclick="myFun()" name="name" id="id"
2. style="style" styleClass="styleClass" value="中国人" url="url"
3. pid="pid" isValidated="true"&gt;
4. 中国人
5. &lt;/h3:input&gt;
6. &lt;h3:input type="button" onclick="myFun()" name="name" id="id"
7. style="style" styleClass="styleClass" value="美国人" url="url"
8. pid="pid" isValidated="true"&gt;
9. &lt;/h3:input&gt;

 

从后台发现打印的InpuTag都是**同一个对象!**

 

发现这个后，我十分担心线程安全问题！比如这些getType();setType(); ！

 

于是就看了下jsp生成的Servlet源代码

Java代码  [![收藏代码](http://klcwt.iteye.com/images/icon_star.png)]()

01. out.write("\\t&lt;body&gt;\\r\\n");
02. out.write("\\t\\t");
03. //调用InputTag
04. if (\_jspx\_meth\_h3\_005finput\_005f0(\_jspx\_page\_context))
05. return;
06. out.write("\\r\\n");
07. out.write("\\t\\t\\r\\n");
08. out.write("\\t\\t");
09. //调用InputTag
10. if (\_jspx\_meth\_h3\_005finput\_005f1(\_jspx\_page\_context))
11. return;
12. out.write("\\r\\n");
13. out.write("\\t&lt;/body&gt;\\r\\n");

 

再接着看\_jspx\_meth\_h3\_005finput\_005f0方法

Java代码  [![收藏代码](http://klcwt.iteye.com/images/icon_star.png)]()

01. private boolean \_jspx\_meth\_h3\_005finput\_005f0(PageContext \_jspx\_page\_context)
02. throws Throwable {
03. PageContext pageContext = \_jspx\_page\_context;
04. JspWriter out = \_jspx\_page\_context.getOut();
05. //  h3:input
06. &lt;span style="color: #ff0000;"&gt; tag.InputTag &lt;span style="color: #0000ff;"&gt;\_jspx\_th\_h3\_005finput\_005f0&lt;/span&gt; = (tag.InputTag) \_005fjspx\_005ftagPool\_005fh3\_005finput\_0026\_005fvalue\_005furl\_005ftype\_005fstyleClass\_005fstyle\_005fpid\_005fonclick\_005fname\_005fisValidated\_005fid.get(tag.InputTag.class);&lt;/span&gt;
07. \_jspx\_th\_h3\_005finput\_005f0.setPageContext(\_jspx\_page\_context);
08. \_jspx\_th\_h3\_005finput\_005f0.setParent(null);
09. // /button2.jsp(12,2) name = type type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
10. \_jspx\_th\_h3\_005finput\_005f0.setType("button");
11. // /button2.jsp(12,2) name = onclick type = java.lang.String reqTime = false required = true fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null    \_jspx\_th\_h3\_005finput\_005f0.setPid("pid");
12. // /button2.jsp(12,2) name = isValidated type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
13. \_jspx\_th\_h3\_005finput\_005f0.setIsValidated("true");
14. int \_jspx\_eval\_h3\_005finput\_005f0 = \_jspx\_th\_h3\_005finput\_005f0.doStartTag();
15. if (\_jspx\_eval\_h3\_005finput\_005f0 != javax.servlet.jsp.tagext.Tag.SKIP\_BODY) {
16. do {
17. out.write("\\r\\n");
18. out.write("\\t\\t中国人\\r\\n");
19. out.write("\\t\\t");
20. int evalDoAfterBody = \_jspx\_th\_h3\_005finput\_005f0.doAfterBody();
21. if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL\_BODY\_AGAIN)
22. break;
23. } while (true);
24. }
25. if (\_jspx\_th\_h3\_005finput\_005f0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP\_PAGE) {
26. &lt;span style="color: #ff0000;"&gt;\_005fjspx\_005ftagPool\_005fh3\_005finput\_0026\_005fvalue\_005furl\_005ftype\_005fstyleClass\_005fstyle\_005fpid\_005fonclick\_005fname\_005fisValidated\_005fid.reuse(\_jspx\_th\_h3\_005finput\_005f0);&lt;/span&gt;
27. return true;
28. }
29. &lt;span style="color: #ff0000;"&gt;    \_005fjspx\_005ftagPool\_005fh3\_005finput\_0026\_005fvalue\_005furl\_005ftype\_005fstyleClass\_005fstyle\_005fpid\_005fonclick\_005fname\_005fisValidated\_005fid.reuse(\_jspx\_th\_h3\_005finput\_005f0);&lt;/span&gt;
30. return false;
31. }

最关键就是这句了,看他如何获得自定义标签对象： tag.InputTag \_jspx\_th\_h3\_005finput\_005f0 = (tag.InputTag) \_005fjspx\_005ftagPool\_005fh3\_005finput\_0026\_005fvalue\_005furl\_005ftype\_005fstyleClass\_005fstyle\_005fpid\_005fonclick\_005fname\_005fisValidated\_005fid.get(tag.InputTag.class);

解释下：

 \_jspx\_th\_h3\_005finput\_005f0 是InputTag 的实例 也就是&lt;h3:input.

而

005fjspx\_005ftagPool\_005fh3\_005finput\_0026\_005fvalue\_005furl\_005ftype\_005fstyleClass\_005fstyle\_005fpid\_005fonclick\_005fname\_005fisValidated\_005

是TagHandlerPool的实例

 

自定义标签是通过这个TagHandlerPool.get 来获取的！

举一反三，有借就有还TagHandlerPool.reuse用来回收这个对象！

 

 

TagHandlerPool.get 

TagHandlerPool.reuse

方法如下：

 

Java代码  [![收藏代码](http://klcwt.iteye.com/images/icon_star.png)]()

01. /\**
02. * Gets the next available tag handler from this tag handler pool,
03. * instantiating one if this tag handler pool is empty.
04. \*
05. * @param handlerClass Tag handler class
06. \*
07. * @return Reused or newly instantiated tag handler
08. \*
09. * @throws JspException if a tag handler cannot be instantiated
10. \*/
11. public Tag get(Class handlerClass) throws JspException {
12. g handler = null;
13. synchronized( this ) {
14. if (current &gt;= 0) {
15. handler = handlers\[current--];
16. return handler;
17. }
18. }
19. // Out of sync block - there is no need for other threads to
20. // wait for us to construct a tag for this thread.
21. try {
22. Tag instance = (Tag) handlerClass.newInstance();
23. AnnotationHelper.postConstruct(annotationProcessor, instance);
24. return instance;
25. } catch (Exception e) {
26. throw new JspException(e.getMessage(), e);
27. }
28. }

 

Java代码  [![收藏代码](http://klcwt.iteye.com/images/icon_star.png)]()

01. /\**
02. * Adds the given tag handler to this tag handler pool, unless this tag
03. * handler pool has already reached its capacity, in which case the tag
04. * handler's release() method is called.
05. \*
06. * @param handler Tag handler to add to this tag handler pool
07. \*/
08. public void reuse(Tag handler) {
09. synchronized( this ) {
10. if (current &lt; (handlers.length - 1)) {
11. handlers\[++current] = handler;
12. return;
13. }
14. }
15. // There is no need for other threads to wait for us to release
16. handler.release();
17. if (annotationProcessor != null) {
18. try {
19. AnnotationHelper.preDestroy(annotationProcessor, handler);
20. } catch (Exception e) {
21. log.warn("Error processing preDestroy on tag instance of "
22. + handler.getClass().getName(), e);
23. }
24. }
25. }

 

 

现在就明白了所有的tag对象都是有一个对象池来维护的，一是方便了重用，而是做到了线程同步。

 

 总结：自定义标签是线程安全的，同时也是可重用的！

 

同时又有另一个疑问

 synchronized( this ) {  
            if (current &gt;= 0) {  
                handler = handlers\[current--];  
                return handler;  
            }  
        }

感觉这种方法可能只能在一个页面上共享，另一个页面上的tag估计是不能共享的！

 

后来看了下生成的servelt代码

如下：

Java代码  [![收藏代码](http://klcwt.iteye.com/images/icon_star.png)]()

1. public void \_jspInit() {
2. \_tagpool = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
3. \_el\_expressionfactory = \_jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory();
4. \_jsp\_annotationprocessor = (org.apache.AnnotationProcessor) getServletConfig().getServletContext().getAttribute(org.apache.AnnotationProcessor.class.getName());
5. }

 可以看到\_tagpool 是根据ServletConifg来生成的

TagHandlerPool.getTagHandlerPool代码如下

Java代码  [![收藏代码](http://klcwt.iteye.com/images/icon_star.png)]()

01. public static TagHandlerPool getTagHandlerPool( ServletConfig config) {
02. TagHandlerPool result=null;
03. String tpClassName=getOption( config, OPTION\_TAGPOOL, null);
04. if( tpClassName != null ) {
05. try {
06. Class c=Class.forName( tpClassName );
07. result=(TagHandlerPool)c.newInstance();
08. } catch (Exception e) {
09. e.printStackTrace();
10. result=null;
11. }
12. }
13. if( result==null ) result=new TagHandlerPool();
14. result.init(config);
15. return result;
16. }