gpt4 book ai didi

java - 我需要每次都创建一个 DocumentBuilderFactory 吗?

转载 作者:行者123 更新时间:2023-11-30 07:49:32 25 4
gpt4 key购买 nike

我需要每 5 分钟从 RSS 源更新一次新闻源。

我写了一个TimerTask,如下所示

public class TimerTaskForAllNews 
{
public static void main( String[] args )
{
TimerTask task = new AllNewsUpdatrUtility();
Timer timer = new Timer();
timer.schedule(task, 1000,60000);
}
}

这是我的TimerTask实现类

package com.util;
import java.net.URL;
public class AllNewsUpdatrUtility extends TimerTask {
private static AllNewsUpdatrUtility instance = null;
public AllNewsUpdatrUtility() {}
public static AllNewsUpdatrUtility getInstance() {
if (instance == null)
instance = new AllNewsUpdatrUtility();
return instance;
}
@Override
public void run() {
try {
JSONArray latestnews = new JSONArray();
JSONObject jsonobj_allnews = new JSONObject();
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
URL url = new URL("http://www.rssmix.com/u/8160628/rss.xml");
Document doc = builder.parse(url.openStream());
NodeList items = doc.getElementsByTagName("item");
for (int i = 0; i < items.getLength(); i++) {
Element item = (Element) items.item(i);
String title = getValue(item, "title");
String link = getValue(item, "link");
String pub_date = getValue(item, "pubDate");

} // for loop ends here

} catch (Exception e) {
e.printStackTrace();
}
}


}

您能让我知道我仍然可以改进这个程序吗?

最佳答案

规范JSR 206 Java™ API for XML Processing (JAXP) 1.4说:

It is expected that the newSAXParser method of a SAXParserFactory implementation, the newDocumentBuilder method of a DocumentBuilderFactory and the newTransformer method of a TransformerFactory will be thread safe without side effects.

正如评论中所述,您可以缓存 DocumentBuilderFactory 实例:

package com.util;
import java.net.URL;
public class AllNewsUpdatrUtility extends TimerTask {
private static AllNewsUpdatrUtility instance;
private final DocumentBuilderFactory dbf;
private AllNewsUpdatrUtility() {}
public synchronized static AllNewsUpdatrUtility getInstance() {
if (instance == null)
instance = new AllNewsUpdatrUtility();
dbf = DocumentBuilderFactory.newInstance();
return instance;
}
@Override
public void run() {
try {
JSONArray latestnews = new JSONArray();
JSONObject jsonobj_allnews = new JSONObject();
DocumentBuilder builder = dbf.newDocumentBuilder();
URL url = new URL("http://www.rssmix.com/u/8160628/rss.xml");
Document doc = builder.parse(url.openStream());
NodeList items = doc.getElementsByTagName("item");
for (int i = 0; i < items.getLength(); i++) {
Element item = (Element) items.item(i);
String title = getValue(item, "title");
String link = getValue(item, "link");
String pub_date = getValue(item, "pubDate");

} // for loop ends here

} catch (Exception e) {
e.printStackTrace();
}
}


}

关于java - 我需要每次都创建一个 DocumentBuilderFactory 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33460413/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com