最近在使用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); } } };
解析xml文件时的调用方法:
docBuildIns.get().parse(File);
get()方法返回此线程局部变量的当前线程副本中的值。如果变量没有用于当前线程的值,则先将其初始化为调用 initialValue() 方法返回的值。