Java並發包——Blockingqueue,ConcurrentLinkedQueue,Executors

來源:互聯網
上載者:User

標籤:線程   throws   文章   packet   load   ext   入隊   發包   cti   

背景

通過做以下一個小的介面系統gate,瞭解一下mina和java並發包裡的東西。A系統為javaweb項目,B為C語言項目,gate是本篇須要完畢的系統。


需求

1. A為叢集系統,並發較高,會批量發送給gate訊息,而且接受gate返回的訊息。

2. gate獨立部署,將從A接受到的訊息壓入隊列,與B建立串連後,將每條訊息驗證簽名等工作後,發送給B。須要保證效能;

3. B負責處理訊息,並返回處理結果,B為gate提供提供六個port,一個port可有三個長串連(須由gate發送心跳保持長串連,否則逾時切斷串連)。

執行個體

項目中用到了兩個架構mina2.0.7和axis2。首先,gate須要接收從A發送過來的訊息。為保證訊息順序性。壓入隊列中。為保證效能。將隊列中的訊息通過不同的串連發送至B,這讓我們非常快就想到了多線程中生產者消費者的那張圖,而且這是一個生產者。多個消費者,以下我們來看代碼。

首先,gate作為服務端,要為A提供一個介面,使用axis2完畢了。關於webservice就不必多說,可看我前面的部落格。配置例如以下:

<serviceGroup><service name="sendService" scope="application">    <description>        SendService    </description>    <messageReceivers>        <messageReceiver mep="http://www.w3.org/2004/08/wsdl/in-only" class="org.apache.axis2.rpc.receivers.RPCInOnlyMessageReceiver"/>        <messageReceiver mep="http://www.w3.org/2004/08/wsdl/in-out" class="org.apache.axis2.rpc.receivers.RPCMessageReceiver"/>    </messageReceivers>    <parameter name="ServiceClass">        cn.net.easyway.customer.SendService    </parameter></service></serviceGroup>

以下是服務實作類別:

import java.util.List;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.LinkedBlockingQueue;import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;import cn.net.easyway.nds.MsgConsumer;import cn.net.easyway.nds.MsgProducer;/** * 為使用者管理系統提供服務介面 * @author yuanfubiao * */public class SendService {private static Log logger = LogFactory.getLog(SendService.class);private static int num = 0;//訊息佇列private static LinkedBlockingQueue<String> msgQueue = new LinkedBlockingQueue<String>();//生產者線程池private static ExecutorService executorProducer = Executors.newFixedThreadPool(20); //建立20個線程。應對並發較高的情況//消費者線程池private static ExecutorService executorCustomer = Executors.newFixedThreadPool(18); //和串連數相應/** * 放入訊息 * @param list 訊息列表 */public void putMsg(List<String> list){//將訊息放入隊列executorProducer.execute(new MsgProducer(msgQueue,list));//取出訊息:資料量大,啟用全部線程if(list.size() > 18){for(int i=0;i<18;i++){executorCustomer.execute(new MsgConsumer(msgQueue));}}else{executorCustomer.execute(new MsgConsumer(msgQueue));}}}

Java並發包為我們提供了非常多有用的多線程東西,因此沒有必要自己去實現一個隊列和線程池。如上面代碼我們用到的隊列是LinkedBlockingQueue,他為安全執行緒的堵塞隊列。多線程操作時不必為了同步而擔心。而且會將進出兩邊自己主動負載,他實現自BlockingQueue介面。

從jdk中能夠看到實現BlockingQueue介面的還有ArrayBlockingQueue,DelayQueue, LinkedBlockingDeque,LinkedBlockingQueue,LinkedTransferQueue,PriorityBlockingQueue,SynchronousQueue;此介面就是提供一個堵塞隊列,從api中我們看到例如以下一張圖:


Throwsexception:當隊列已滿。再次加入會拋出錯誤,取資料也是如此。

Specialvalue:加入或取出時會有一個傳回值;

Blocks:是在隊列已滿或為空白時,會一直堵塞;

Time Out:指堵塞到一定時間。線程退出。

當中,另一個並發隊列也是作為生產者消費者的首選:ConcurrentLinkedQueue,它是非堵塞隊列。肯定就不是出自Blockingqueue介面,而是出自AbstractQueue,因此也就沒有put和take方法,使用這個並發隊列須要有兩點注意:第一。推斷是否為空白盡量使用isEmpty方法。不要用size()。有人測試過size方法非常耗費時間。第二就是線程問題。儘管ConcurrentLinkedQueue是安全執行緒的,可是僅僅負責原子性的。就是說當你操作queue.add() or queue.poll的時候是安全的。當並發量較大時,你在使用queue.isEmpty時還不為空白,但就在這空當有可能就運行poll操作。導致隊列為空白引起異常,可用例如以下代碼:

synchronized(queue) {    if(!queue.isEmpty()) {       queue.poll();    }}

在gate中。我定義了兩個線程池。一個是生產者。還有一個是消費者:

//生產者線程池private static ExecutorService executorProducer = Executors.newFixedThreadPool(20); //建立20個線程。應對並發較高的情況//消費者線程池private static ExecutorService executorCustomer = Executors.newFixedThreadPool(18); 

Executors提供了一個Factory 方法,用來建立線程池。返回的線程池都實現了ExecutorService介面,能夠建立例如以下線程池:

newCachedThreadPool():建立一個可快取的線程池,調用execute將重用曾經構造的線程。假設如今線程沒有可用的,則建立一個新線程加入到池中,終止並從緩衝中溢出那些已有60秒未被使用的線程;

newFixedThreadPool(intnThreads):建立固定的線程;

newScheduledThreadPool(intcorePoolSize):建立一個支援定時及周期性的任務啟動並執行線程池;

newSingleThreadExecutor():建立一個單線程的Executor。

啟動線程。有兩個方法。一個是execute(),還有一個是submit(),後者是有傳回值的,會將啟動並執行結果Future返回,關於Future可移步這裡。

以下就是生產者和消費者代碼:

生產者:

import java.util.Iterator;import java.util.List;import java.util.concurrent.LinkedBlockingQueue;/** * 向隊列加入訊息 * @author yuanfubiao * */public class MsgProducer implements Runnable {private LinkedBlockingQueue<String> msgQueue;private List<String> message;public MsgProducer(LinkedBlockingQueue<String> queue,List<String> msg) {this.msgQueue = queue;this.message = msg;}@Overridepublic void run() {Iterator<String> iter = message.iterator();while(iter.hasNext()){String msg = iter.next();try {msgQueue.put(msg);} catch (InterruptedException e) {e.printStackTrace();}}}}

消費者:

import java.text.SimpleDateFormat;import java.util.Date;import java.util.concurrent.LinkedBlockingQueue;import nds.framework.security.NDSMD5;import org.apache.commons.codec.binary.Hex;import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;import org.apache.mina.core.session.IoSession;/** * 從訊息佇列取出訊息 * @author yuanfubiao * */public class MsgConsumer implements Runnable{private static Log logger = LogFactory.getLog(MsgConsumer.class);private LinkedBlockingQueue<String> msgQueue;public MsgConsumer(LinkedBlockingQueue<String> queue) {this.msgQueue = queue;}@Overridepublic void run() {while(!msgQueue.isEmpty()){String msg = null;try {msg = msgQueue.take();} catch (InterruptedException e) {e.printStackTrace();}if(null == msg){return;}//增加時間SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");String now = format.format(new Date());String prefix = msg.substring(0, 19);String suffix = msg.substring(33, msg.length());String packet = prefix.trim() + now.trim() + suffix.trim();//簽名部分忽略        //TODOString newStr = packet  // 簽名 + signature.toUpperCase().trim();//關於mina,可見我下篇文章IoSession session = SessionPool.getSession(newStr.substring(13, 15));logger.info("發送資料:" + newStr);session.write(newStr);try {Thread.sleep(1000); //等待一秒} catch (InterruptedException e1) {e1.printStackTrace();}}}}

原始碼下載:http://download.csdn.net/detail/stubbornpotatoes/7438435好文推薦:http://blog.csdn.net/defonds/article/details/44021605

Java並發包——Blockingqueue,ConcurrentLinkedQueue,Executors

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.