用LinkedList实现的一个数据缓冲区

     在做一个解析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 {
					// 处理异常
				}
			}
		}

	}

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值