編程生活

             :: 首頁 :: 新隨筆 :: 聯系 :: 聚合  :: 管理 ::
            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)

           

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

           

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


          fParseInProgress 
          = true;

          // 解析xml文件

          finally {
              fParseInProgress 
          = false;
          }

           

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

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

          還有一種方法是創建一個DocumentBuilder類型的ThreadLocal變量,這樣子每個線程都擁有自己的DocumentBuilder對象,能夠同時轉換多個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 閱讀(6538) 評論(0)  編輯  收藏

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


          網站導航:
           
          主站蜘蛛池模板: 博白县| 大厂| 浦北县| 南华县| 三亚市| 新邵县| 青龙| 阜城县| 岳西县| 上林县| 留坝县| 呼玛县| 枝江市| 织金县| 柳州市| 靖边县| 尖扎县| 嘉定区| 准格尔旗| 通州市| 奈曼旗| 西城区| 肃宁县| 绥德县| 新兴县| 吕梁市| 秦安县| 奉节县| 盘山县| 屏东县| 青田县| 东源县| 临汾市| 神农架林区| 小金县| 丹凤县| 承德市| 桦甸市| 始兴县| 河池市| 石泉县|