用LinkedList实现的一个数据缓冲区
来源:互联网 发布:c语言实例好书 知乎 编辑:程序博客网 时间:2024/05/18 06:14
在做一个解析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 writerxmlQueue.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 {// 处理异常}}}}}
- 用LinkedList实现的一个数据缓冲区
- 一个简单的环形缓冲区的实现
- 实现了一个 native层读写音频数据时用到的一个 音频数据缓冲区(线程安全的)(c++)
- 一个免锁环形缓冲区的实现
- geotools实现shp数据的缓冲区分析
- Java实现一个简单的链表结构------LinkedList
- DataWindow的数据缓冲区
- DataWindow的数据缓冲区
- DataWindow的数据缓冲区
- “麻烦”的数据缓冲区
- DataWindow的数据缓冲区
- DataWindow的数据缓冲区
- DataWindow的数据缓冲区
- 使用双缓冲区实现的一个小球碰壁Applet
- 编写一个应用程序,要求将LinkedList创建的对象写入文件,在读出一个LinkedList节点中的数据。
- 用LinkedList实现statck的功能
- 举例说明用LinkedList实现栈的方法
- Java用LinkedList实现的Stack
- c++ learning blog (1)
- 浅析Ruby on Rails部署方案
- 个人创业者六大死穴,来检查一下自己
- const 详讲 (转)
- C++/OOP 大系
- 用LinkedList实现的一个数据缓冲区
- WEB中加载ApplicationContext的两种方式
- 学习PowerShell的好地方
- jsp基础语法
- 2008百度之星第二场初赛题目
- 中小企业IT建设的小看法5
- 中小企业IT建设的小看法6
- 使用access数据库读取DataReader注意事项
- 简单好用的读写ini文件的类