Java Asynchronous Processing Simple Practice

Source: Internet
Author: User

Java Asynchronous Processing Simple Practice

Http://www.cnblogs.com/fangfan/p/4047932.html

Synchronous vs. asynchronous

Usually synchronization means that one process of a task is serialized on multiple threads, while asynchrony means that a process can allow multiple threads to process simultaneously.

Asynchrony typically represents better performance because it relies heavily on buffering and is typically used for space-time, for example, in a computer where the cache acts as a buffer between CPU and disk IO to coordinate CPU high-speed computing power and low-speed read and write capability of the disk.

Volatile

Scenario: Check that an app performs a shutdown or interrupt state. Because this keyword rejects the virtual optimization of a variable multiple assignments, it ensures that the virtual machine must check the state of the variable modified by the keyword.

Countdownlatch

Scenario: controls that the current thread is waiting until a set of thread operations finishes executing. For example, executing the await () method in the main thread blocks the main thread and executes the countdown () method after the worker thread finishes executing the logic.

The sample scenario for this article:

1, send a message from the console to the messaging server (simulated by a queue).

2. Write Message Queuing to a file (set the delay to write the file to simulate a performance bottleneck).

3, the message server acts as a buffer between the console and the file write.

Example code:

Note: Adding a message to a message queue can be added through a for loop, this article uses console input to make it easier to observe the changes in the file and queue, and the actual write line file record should be faster than the hand speed, so the thread sleep time is increased in this example.

Package Org.wit.ff.ch2;import Java.io.bufferedwriter;import Java.io.file;import java.io.filewriter;import Java.io.ioexception;import Java.util.scanner;import Java.util.concurrent.blockingqueue;import Java.util.concurrent.countdownlatch;import Java.util.concurrent.linkedblockingqueue;import Java.util.concurrent.TimeUnit;/** * * <pre> * Simple Asynchronous processing example. * </pre> * * @author F.fang * @version $Id: Asynchandler.java, v 0.1 October 23, 2014 PM 11:37:54 F.fang EXP $*/PublicClassAsynchandler {/** * Control resource release.*/PrivateCountdownlatch latch;/** * Process completion identification.*/PrivateVolatileBoolean handlefinish;/** * Message written to local file complete.*/PrivateVolatileBoolean sendfinish;/** * Block queue.*/Private blockingqueue<string>QueuePrivateBufferedWriter bw;PublicAsynchandler (Countdownlatch latch) {This.latch =Latch/** * Use linked list to implement.*/Queue =New linkedblockingqueue<string>(); File File =New File ("E:/hello.txt");Try{bw =New BufferedWriter (NewFileWriter (file)); }Catch(IOException e) {ThrowNewRuntimeException (e); } }PublicvoidHandle () {//Simulation of performance bottlenecks in the execution process, 3s processing a message.NewThread () {PublicvoidRun () {while (!Handlefinish) {Try{TimeUnit.SECONDS.sleep (3); }Catch(Interruptedexception E1) {//Do not do the processing.} String s =Queue.peek ();if (s! =Null) {Queue.poll ();Try{Bw.write (s); Bw.newline ();}Catch(IOException e) { } }//If the queue is empty and the message is sent to completion.if (Queue.isempty () &&Sendfinish) {//Counter 1->0Latch.countdown ();//Let the processing process end. Handlefinish =True;Break; }}}}.start (); }/** * * <pre> * Give the identification of the completion of the message sending. * </pre> **/PublicvoidSendfinish () {sendfinish =True; }/** * * <pre> * Resource release. * </pre> **/PublicvoidRelease () {System.Out.println ("release!");if (BW! =Null) {Try{Bw.close ();}Catch(IOException e) {//TODO Print log.} }//In fact, using queue = null is enough.if (Queue! =Null) {queue.clear (); queue =Null; } }/** * * <pre> * Send message to queue. * </pre> * * @param text*/PublicvoidSendmsg (String text) {if (Text! =Null &&!Text.isempty ()) {queue.add (text);}}PublicStaticvoidMain (string[] args) {Countdownlatch latch =New Countdownlatch (1); Asynchandler handler =NewAsynchandler (latch); Handler.handle ();//Do a check. Scanner Scanner =New Scanner (System.Inch);while (True) {String Text =Scanner.next ();//If the user chooses to exit.if ("Exit".equals (text)) {// Handler.sendfinish (); breaktry {// The blocking main thread waits for the message to be written to the local file to complete. Latch. await ();} catch (Interruptedexception e) {e.printstacktrace ();} //// Close the console input.  Scanner.close (); }} 

Java Asynchronous Processing Simple Practice

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.