編程生活

             :: 首頁 :: 新隨筆 :: 聯(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 閱讀(6538) 評論(0)  編輯  收藏

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


          網(wǎng)站導(dǎo)航:
           
          主站蜘蛛池模板: 瑞昌市| 徐汇区| 尉氏县| 徐闻县| 鄂州市| 开原市| 邳州市| 阿坝县| 赤水市| 龙山县| 竹山县| 潢川县| 龙口市| 常熟市| 无锡市| 峡江县| 南昌县| 汉沽区| 咸阳市| 金乡县| 浮山县| 岑巩县| 虎林市| 荔波县| 新沂市| 福贡县| 历史| 弋阳县| 林周县| 丽水市| 新化县| 咸阳市| 敖汉旗| 东宁县| 逊克县| 南京市| 台安县| 云梦县| 安远县| 郎溪县| 五大连池市|