Use of Java-blockingqueue

Source: Internet
Author: User

Each time is a long time to write something in the blog, say that they are busy, it is to give their own an excuse, in fact, or lazy ah. Hey...

In the recent project there is a need to get the parameters from the log file, and then call the different APIs to compare the results. But I do not know in what way is better, so check out the JDK Handbook, found blockingqueue this good thing.

About the introduction of Blockingqueue, everyone interested can see for themselves: http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/LinkedBlockingQueue.html

The need is simply to put the parameters into the queue and then go to the next strategy to consume. At first, the data is stored in the queue by different threads, and then returned to the next service a Blockingqueue object, the next policy is consumed from the queue, code is as follows:

@SuppressWarnings ("Rawtypes") @Overridepublic blockingqueue gettxtlogcontent (String path) {File File = new file (path); BufferedReader reader = null; String tempstr = null;final blockingqueue queue = new Linkedblockingqueue (); try {reader = new BufferedReader (New Filereade R (file)); while ((TempStr = Reader.readline ()) = null) {Final inputoutputprameters parameter = new Inputoutputprameters () ; string[] List = Tempstr.split (";"); if (list = null && list.length > 0) {parameter.setinputparamters (list[0]);p arameter.setoutputparameters ( LIST[1]);} New Thread () {@SuppressWarnings ("unchecked") public void Run () {try {Thread.Sleep ((long) (Math.random () *100)); log.info ("Start depositing data!") "); queue.put (parameter); Log.info (" The data is already in the queue, there is "+ queue.size () +" Queue! Input parameters: "+ parameter.getinputparamters () +"; \ n Output parameters: "+ parameter.getoutputparameters ());} catch (Exception e) {log.error ("System exception:" + E);}}}. Start ();} Reader.close ();} catch (FileNotFoundException e) {e.printstacktrace ();} catch (IOException e) {e.printstacktRace ();} finally {if (reader! = null) {try {reader.close ()} catch (Exception e) {e.printstacktrace ();}}} return queue;}

However, in the actual operation, because the log is larger, the next strategy may have to wait 1hour or more time to start processing, which is obviously not in line with the requirements, and then optimized the next, the blockingqueue changed to global static, Then the next policy can directly monitor whether there are values in this queue, consume with values, block threads waiting or timeout, and other processing.

The improved Code:

1. Create a new Queue class:

public class Parameterqueue extends linkedblockingqueue<inputoutputprameters> {/** * @Fields serialversionuid: */ Private static final Long Serialversionuid = 6032356446145302484l;private static blockingqueue<inputoutputprameters > queue = new linkedblockingqueue<inputoutputprameters> ();/** * @Fields log: Logging */private static final Logger l og = Loggerfactory.getlogger (parameterqueue.class);/** * Gets the object in the queue * @Method: GetParameter * @Description: Gets the object in the queue * @re Turn gets the object information */public static Inputoutputprameters getparameter () {inputoutputprameters result = null;try {result = (Input outputprameters) Queue.take ();} catch (Exception e) {log.error ("Get queue exception, exception information:" + e);} return result;} /** * Gets the number of queues * @Method: Getqueuesize * @Description: Gets the number of queues * @return number */public static Integer getqueuesize () {return Queue.size ();} /** * Place parameters into the queue * @Method:p utparameter * @Description: Place parameters into the queue * @param parameter objects to be placed */public static void Putparamet ER (inputoutputprameters parameter) {try {quEue.put (parameter);} catch (Exception e) {log.error ("Insert queue exception, exception information:" + e);}}}

2, read the file, directly manipulate the queue, put the value into the queue, the next policy from the queue get value, put code as follows:

public void GetSource (String path) {try {File file = new file (path); BufferedReader reader = null;  String TempStr = null;try {reader = new BufferedReader (new FileReader (file)); while ((TempStr = Reader.readline ()) = null) {Final Inputoutputprameters parameter = new Inputoutputprameters (); string[] List = Tempstr.split (";"); if (list = null && list.length > 0) {parameter.setinputparamters (list[0]);p arameter.setoutputparameters ( LIST[1]);} Putinqueue (parameter);} Reader.close ();} catch (FileNotFoundException e) {e.printstacktrace ();} catch (IOException e) {e.printstacktrace ();} finally {if (reader! = null) {try {reader.close ()} catch (Exception e) {e.printstacktrace ();}}}} catch (Exception e) {log.error ("System exception:" + E);}}  /** * Store parameters in Queue * @Method:p utinqueue * @Description: Store parameters in Queue * @param parameter objects to be stored */private void Putinqueue (final Inputoutputprameters parameter) {new Thread () {public void run () {try {Thread.Sleep ((long) (Math.random () *100)); Log.info ("Start depositing data! "); ParametErqueue.putparameter (parameter); Log.info ("The data is already in the queue, now there are" + parameterqueue.getqueuesize () + "Queues! Input parameters: "+ parameter.getinputparamters () +"; \ n Output parameters: "+ parameter.getoutputparameters ());} catch (Exception e) {log.error ("System exception:" + E);}}}. Start ();}

  

So the request was met. Keep a record of this small requirement for later inspection.

Briefly, Blockingqueue is thread-safe, commonly used is arrayblockingqueue, linkedblockingqueue

Arrayblockingqueue need to develop capacity, and linkedblockingqueue does not need

While in consumption, take () is blocking the thread, if it is a single-threaded run, takes () when the entire thread on the card

So look at the specific environmental needs, is to take or other, I generally use poll, because you can set the time-out period.

Oh, I don't know how to write it, that's all.

Use of Java-blockingqueue

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.