在做一个解析XML文件的功能时,发现处理XML文件并做其它操作的时候,如果无限制的把XML文件放到LIST中,等待处理,当放入LIST中的速度过快,而解析处理XML效率过低时,会导致内存溢出的错误。遂写了一个数据缓冲区解决上述问题!源码如下:
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
//存放XML文件的一个缓冲区
public class XmlBuffer implements Runnable {
// 实际存放文件的链表
public static List xmlQueue = Collections
.synchronizedList(new LinkedList());
// 队列的当前长度
public static long indicator = 0;
// 队列的最大长度
public static final long BUF_LIMIT = 500000000;
public XmlBuffer() {
}
private String name = "";
public XmlBuffer(String threadName) {
this.name = threadName;
}
public String getName() {
return this.name;
}
public void enqueue(byte[] data, String type) {
XmlEntity newXml = new XmlEntity();
newXml.setContent(data);
newXml.setType(type);
synchronized (xmlQueue) {
// 判断当前队列是否已经满了。如果没有空间了,等待
for (;;) {
if (this.indicator > BUF_LIMIT
|| this.indicator + data.length > BUF_LIMIT) {
try {
xmlQueue.wait();
} catch (InterruptedException ie) {
// 处理对应的异常
}
} else {
break;
}
}
}
synchronized (xmlQueue) {
xmlQueue.add(newXml);
this.indicator += newXml.length();
xmlQueue.notifyAll();
}
}
class XmlEntity {
void put_dataRaw() {
dealData(this.content, this.type);
}
private void dealData(byte[] buf, String type) {
// 处理业务
}
XmlEntity() {
}
public void setContent(byte[] content) {
this.content = content;
}
public byte[] getContent() {
return content;
}
public int length() {
return content.length;
}
public void setType(String type) {
this.type = type;
}
public String getType() {
return this.type;
}
private byte[] content;
private String type = "";
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
}
// 在队列中取出XML文件,并做相应的处理
public void run() {
for (;;) {
synchronized (xmlQueue) {
for (;;) {
try {
if (indicator <= 0) {
// wait for data writer
xmlQueue.wait();
} else {
break;
}
} catch (InterruptedException ex) {
// 处理对应的异常
}
}
}
try {
XmlEntity xml = null;
synchronized (xmlQueue) {
xml = (XmlEntity) xmlQueue.remove(0);
this.indicator -= xml.length();
xmlQueue.notifyAll();
}
if (xml == null) {
continue;
}
// 针对XML文件进行操作
xml.put_dataRaw();
} catch (Exception e) {
if (e instanceof IndexOutOfBoundsException) {
continue;
} else {
// 处理异常
}
}
}
}
}