Java and Contract--blockingqueue,concurrentlinkedqueue,executors

Source: Internet
Author: User

Background

Learn about the Mina and java concurrency package by doing one of the following small interface system Gate. a system for the Javaweb project,B for the C language project,Gate is the need to complete the system.


Demand

1. A as a clustered system, high concurrency is sent to the gate message in bulk, and the message returned by the gate is accepted.

2.   gate Independent deployment, will be from the a received messages into the queue, and b to establish a connection, after each message verification of the signature, such as work, Sent to b . need to ensure performance;

3. B is responsible for processing the message, and returns the processing result,B provides six ports for Gate , one port can have three long connections (must be sent by the Gate heartbeat to maintain a long connection, otherwise time-out disconnection).

Instance

Two frames mina2.0.7 and Axis2were used in the project. First, thegate needs to receive messages sent from a . To guarantee the order of messages. Pressed into the queue. To ensure performance. Sending messages in a queue to Bthrough different connections makes it very quick to think of the graph of the producer consumer in multi-threading, and this is a producer. Multiple consumers, let's look at the code below.

First,Gate as the service side, to provide an interface for a , the use of Axis2 is complete. There is no need to say more about WebService , but look at my previous blog. Configuration such as the following:

<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>

The following are the service implementation classes:

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;/** * Provides service interface for user Management system * @author Yuanfubiao * */public class Sendservice {private static Log L Ogger = Logfactory.getlog (sendservice.class);p rivate static int num = 0;//Message Queue private static linkedblockingqueue< string> msgqueue = new linkedblockingqueue<string> ();//producer thread pool private static Executorservice Executorproducer = Executors.newfixedthreadpool (20); Create a 20 thread. Coping with high concurrency//consumer thread pool private static Executorservice Executorcustomer = Executors.newfixedthreadpool (18); and the number of connections corresponding/** * put messages * @param list */public void putmsg (list<string> list) {//Put messages into queue Executorproducer.execute ( New Msgproducer (msgqueue,list));//Remove message: Large amount of data, enable all threads if (List.size () >) {for (int i=0;i<18;i++) {Executorcustomer.execute (New Msgconsumer (Msgqueue));}} Else{executorcustomer.execute (New Msgconsumer (Msgqueue));}}

Java and the contract gives us a lot of useful multi-threaded things, so there is no need to implement a queue and thread pool. As the above code we use the queue is linkedblockingqueue, he is a thread-safe blocking queue. Multi-threaded operations do not need to be worried about synchronization. and will be in and out on both sides of their own active load, he realized from the blockingqueue interface.

From the JDK you can see the arrayblockingqueue,delayqueue, Linkedblockingdeque, that implements the Blockingqueue interface, Linkedblockingqueue,linkedtransferqueue,priorityblockingqueue,synchronousqueue; This interface is to provide a blocking queue from the API we see, for example, the following picture:


throwsexception : When the queue is full. Joining again throws an error, as is the case for data fetching.

Specialvalue : There will be a return value when added or removed;

Blocks : is blocked until the queue is full or empty;

time out : Refers to the blockage to a certain time. Thread exits.

, another concurrent queue is also preferred as a producer consumer:Concurrentlinkedqueue, which is a non-clogging queue. Certainly not from the blockingqueue interface, but from the abstractqueue, so there is no put and take method, the use of this concurrent queue requires two points to note: first. Infer whether to use the isEmpty method as empty as possible. Do not use size (). Someone has measured the size method is very time-consuming. The second is threading issues. Although concurrentlinkedqueue is thread-safe, it is only responsible for atomicity. That means it's safe when you operate Queue.add () or Queue.poll . When the concurrency is large, you are not empty when you use queue.isempty , but it is possible to run the poll operation in this space. Causing the queue to be empty causes an exception to be available, such as the following code:

Synchronized (queue) {    if (!queue.isempty ()) {       queue.poll ();}    }

In the gate . I have defined two thread pools. One is the producer. There is also a consumer:

Executors provides a factory method to create a thread pool. The returned thread pool implements the Executorservice interface, which can be created for example with a thread pool:

Newcachedthreadpool () : Creates a cacheable thread pool that calls execute to reuse the threads that were once constructed. Assuming that the thread is not available today, create a new thread to join the pool, terminate and overflow the threads from the cache that have not been used for a few seconds;

Newfixedthreadpool (intnthreads) : Create a fixed thread;

Newscheduledthreadpool (intcorepoolsize) : Create a thread pool that supports timed and recurring task runs;

Newsinglethreadexecutor () : Create a single thread of Executor.

Start the thread. There are two methods. One is execute (), and the other is submit (), which has a return value, which will return the result of the run, and the future is here .

Here is the producer and consumer code:

Producers:

Import Java.util.iterator;import java.util.list;import java.util.concurrent.linkedblockingqueue;/** * Add message to queue * @ 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 ()}}}

Consumers:

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;/** * Remove message from message queue * @author Yuanfubiao * */public class Msgconsumer implements runnable{private static Log logger = Logfactory.getlog (Msgconsumer.cla SS);p rivate 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 (Interruptede Xception e) {e.printstacktrace ();} if (null = = msg) {return;} Add time SimpleDateFormat format = new SimpleDateFormat ("Yyyymmddhhmmss"); String now = Format.format (New Date ()); String prefix = msg.substring (0, 19); String suffix = msg.substring (, msg.length ()); String packet = Prefix.trim() + Now.trim () + Suffix.trim ();//The signature section ignores//todostring NEWSTR = packet//signature + signature.touppercase (). Trim ();//About M Ina, see my next article iosession session = Sessionpool.getsession (newstr.substring); Logger.info ("Send data:" + newstr); Session.write (NEWSTR); try {thread.sleep (1000);//wait One second} catch (Interruptedexception E1) {e1.printstacktrace ();}}}

Source code Download: http://download.csdn.net/detail/stubbornpotatoes/7438435 Good Article recommendation: http://blog.csdn.net/defonds/article/details/44021605

Java and Contract--blockingqueue,concurrentlinkedqueue,executors

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.