編程生活

             :: 首頁 :: 新隨筆 :: 聯(lián)系 :: 聚合  :: 管理 ::
            113 隨筆 :: 0 文章 :: 18 評論 :: 0 Trackbacks

           

          最近在使用javax.xml.parsers.DocumentBuilder解析xml文件的時候偶爾會出錯:

           

          org.xml.sax.SAXException: FWK005 parse may not be called while parsing.
                  at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(DOMParser.java:
          263)
                  at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(DocumentBuilderImpl.java:
          284)
                  at javax.xml.parsers.DocumentBuilder.parse(DocumentBuilder.java:
          208)

           

          跟蹤了一下代碼,發(fā)現(xiàn)這個異常是在com.sun.org.apache.xerces.internal.parsers.DTDConfiguration.parse(DTDConfiguration.java:546)拋出來的。該段代碼結(jié)構(gòu)如下:

           

          if(fParseInProgress) {
              
          throw new XNIException("FWK005 parse may not be called while parsing.");
          }


          fParseInProgress 
          = true;

          // 解析xml文件

          finally {
              fParseInProgress 
          = false;
          }

           

          從程序邏輯來看,如果當(dāng)前DocumentBuilder對象正在轉(zhuǎn)換文檔,此時再次請求轉(zhuǎn)換文檔,那么直接拋出XNIException(“FWK005 parse may not be called while parsing.”);異常。

          這個問題也比較好解決,一種是對轉(zhuǎn)換xml文檔的方法,增加synchronized關(guān)鍵字,這樣子不會有兩個線程同時訪問方法。

          還有一種方法是創(chuàng)建一個DocumentBuilder類型的ThreadLocal變量,這樣子每個線程都擁有自己的DocumentBuilder對象,能夠同時轉(zhuǎn)換多個xml文件。代碼如下:

           

          private static ThreadLocal docBuildeIns = new ThreadLocal() {
              
          protected DocumentBuilder initialValue() {
                  
          try {
                      
          return DocumentBuilderFactory.newInstance().newDocumentBuilder();
                  }
           catch (ParserConfigurationException e) {
                      String msg 
          = "DocumentBuilder 對象初始化失??!";
                      log.error(msg, e);
                      
          throw new IllegalStateException(msg, e);
                  }

              }

          }
          ;

           

          posted on 2012-05-09 17:18 wilesun 閱讀(6519) 評論(0)  編輯  收藏

          只有注冊用戶登錄后才能發(fā)表評論。


          網(wǎng)站導(dǎo)航:
           
          主站蜘蛛池模板: 海丰县| 泾川县| 登封市| 新沂市| 小金县| 饶平县| 永胜县| 郧西县| 西华县| 大冶市| 翼城县| 商南县| 舟山市| 手机| 临清市| 涿州市| 平武县| 浮梁县| 丰宁| 卢氏县| 札达县| 健康| 建湖县| 思茅市| 山阳县| 平定县| 永丰县| 汉川市| 蓝山县| 荥经县| 大新县| 井研县| 咸宁市| 衡山县| 抚州市| 达拉特旗| 巴彦县| 麦盖提县| 剑河县| 建阳市| 和静县|