解决并发大数据量阻塞之道的重要思想是:
利用多线程将数据接收和数据处理两块业务分开。1、数据接收
public class MessageReceiver{
//建立数据缓存区
private List messageList = new ArrayList();
//添加消息至数据缓冲区
public void addMessage(ESBInput inputMessage) {
synchronized(messageList) {
messageList.add(inputMessage);
messageList.notifyAll();
}
}
//并发数据接收入口,调用添加数据方法,而不是直接操作inputMessage,对其解析或者别的操作,不然极可能造成阻塞
public void handleMessage(Input inputMessage) {
addMessage(inputMessage);
}
//从数据缓冲区取数据,它应该被另外一个线程调用
public List getMessageList() {
List _processList = new ArrayList();
try {
synchronized (messageList) {
while (messageList.size() == 0) {
messageList.wait();
}
_processList.addAll(messageList);
//清空缓存区
messageList.clear();
}
}
catch (Exception ex) {
ex.printStackTrace();
}
return _processList;
}
}
2、数据处理
//线程
public class MessageProcessThread extends Thread {
MessageReceiver receiver;
public MessageProcessThread (MessageReceiver receiver){
this.receiver=receiver;
}
public void run() {
while (true) {
List list = receiver.getMessageList();
while (iter.hasNext()) {
//do what you want....
handleMessage((Input)list .next());
try {
sleep (100);
}
catch (Exception ex) {
}
}
}
}
public handleMessage(Input messsage){
//处理消息
}
posted on 2009-01-06 10:28
蒋家狂潮 阅读(953)
评论(0) 编辑 收藏 所属分类:
Basic