1. Scene
The recent project has encountered a small problem: from the foreground submission to the server A,a call service side B processing time-out, because the front-end request to the DB Plug 10,000 data, after the plug-in to clean up the cache, send messages.
The server has an operation A, a, B, clean cache C, send messages. 10,000 of the data, said not much, said a lot less. and not just insert. It's no surprise that there is a timeout.
2. Analysis
How do I avoid timeouts? One request processing spicy data, processing 100 data per request, multiple requests processing, can effectively resolve the timeout problem. To not affect the user's experience, the request is changed to an AJAX asynchronous request.
In addition, careful analysis of the scene. A operation is the core of this process. The B and C operations can be handled asynchronously. In other words, a operation can be returned to the result immediately after processing, do not have to wait for B, C and then return. b, C operations can be placed on an asynchronous task to handle.
3. Actual combat
(1), Executorservice: Task submission
(2), demo
Asynchronous task classes
Public classExecutordemo {PrivateExecutorservice executor = Executors.newfixedthreadpool (1); Public voidAsyntask ()throwsinterruptedexception {executor.submit (NewRunnable () {@Override Public voidrun () {Try{Thread.Sleep (10000);//easy to observe results}Catch(interruptedexception e) {e.printstacktrace (); } intsum = 0; for(inti = 0; i < 1000; i++) {sum+=i; } System.out.println (sum); } }); }}
Client Impersonation
Public classClient { Public Static voidMain (string[] args)throwsinterruptedexception {BooleanR =Task2 (); if(R) {task3 (); } System.out.println ("------------Main End-----------"); } Static BooleanTask2 ()throwsinterruptedexception {Executordemo e=NewExecutordemo (); E.asyntask (); System.out.println ("------------Task2 End-----------"); return true; } Static voidTASK3 ()throwsinterruptedexception {intj = 0; while(true) { if(j + + > 10000) { Break; }} System.out.println ("------------Task3 End-----------"); }}
The result is Jiangzi.
------------Task2 End-----------------------Task3 end-----------------------main end-----------499500
We analyze the results, TASK2 is an asynchronous task, execute to Task2, the main thread will not be blocked in Task2, do not wait for task2 processing, you can go down task3.
Java Asynchronous Task Processing