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 a typical use of space-time-based approaches, such as caching in a computer as a buffer between CPU and disk IO to coordinate CPU high-speed computing power and low-speed disk read and write capabilities.
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 $*/ Public classAsynchandler {/** * Control resource release. */ PrivateCountdownlatch latch; /** * Process completion identification. */ Private volatileBoolean handlefinish; /** * Message written to local file complete. */ Private volatileBoolean sendfinish; /** * Block queue. */ PrivateBlockingqueue<string>queue; Privatebufferedwriter bw; PublicAsynchandler (Countdownlatch latch) { This. Latch =latch; /** * Use linked list to implement. */Queue=NewLinkedblockingqueue<string>(); File File=NewFile ("E:/hello.txt"); Try{BW=NewBufferedWriter (NewFileWriter (file)); } Catch(IOException e) {Throw NewRuntimeException (e); } } Public voidhandle () {//simulation of performance bottlenecks in the execution process, 3s processing a message. NewThread () { Public voidrun () { 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> **/ Public voidSendfinish () {sendfinish=true; } /** * * <pre> * Resource release. * </pre> **/ Public voidrelease () {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*/ Public voidsendmsg (String text) {if(Text! =NULL&&!Text.isempty ()) {Queue.add (text); } } Public Static voidMain (string[] args) {Countdownlatch latch=NewCountdownlatch (1); Asynchandler Handler=NewAsynchandler (latch); Handler.handle (); //do a check.Scanner Scanner =NewScanner (System.inch); while(true) {String text=Scanner.next (); //if the user chooses to exit. if("Exit". Equals (text)) { //indicates that the message has been sent for completion.Handler.sendfinish (); Break; } handler.sendmsg (text); } Try { //the blocking main thread waits for the message to be written to the local file to complete.Latch.await(); } Catch(interruptedexception e) {e.printstacktrace (); } //frees the resource file stream, queue.handler.release (); //close the console input.Scanner.close (); }}
Java Asynchronous Processing Simple Practice