In the process of program development, there are often such a situation, the program first executed method1 get results result1, in the implementation of METHOD2 get results result2, and then according to RESULT1 and RESULT2 results to determine the next step of the implementation of the program. Here method1 and method2 are unrelated, that is, method1 execution and method2 execution positions can be adjusted without affecting the execution results of the program.
1. Serial Program
In the traditional sense of writing, we often get the serial execution of the program form, the total execution time of the program is METHOD1 execution time time1 plus method2 execution time time2, so the total execution time time=time1+time2. We get the serial program form.
Import Com.yang.domain.BaseResult;
Import Org.junit.Test;
Import Java.util.concurrent.TimeUnit; /** * @Description: * @Author: yangzl2008 * @Date: 2016/1/9 19:06/public class serial {@Test public void
Test () {Long start = System.currenttimemillis ();
Baseresult BASERESULT1 = method1 ()//time-consuming operation 1, time time1 baseresult baseResult2 = METHOD2 ();/time-consuming operation 2, time time2
Long end = System.currenttimemillis (); Total time elapsed = time1 + time2 System.out.println ("BASERESULT1 is" + BASERESULT1 + "\NBASERESULT2 is" + baseResult2
+ "\ntime Cost is" + (End-start);
Private Baseresult method1 () {Baseresult baseresult = new Baseresult ();
try {TimeUnit.SECONDS.sleep (1);
catch (Interruptedexception e) {e.printstacktrace ();
} baseresult.setcode (1);
Baseresult.setmsg ("method1");
return baseresult; Private Baseresult Method2 () {BasEresult Baseresult = new Baseresult ();
try {TimeUnit.SECONDS.sleep (1);
catch (Interruptedexception e) {e.printstacktrace ();
} baseresult.setcode (1);
Baseresult.setmsg ("Method2");
return baseresult; }
}Execution results:
BASERESULT1 is baseresult{code=1, msg= ' method1 '}
baseResult2 is baseresult{code=1, msg= ' method2 '}
2000
2, serial program of multithreading transitionAnd this code is not a place to optimize. Accelerate program execution efficiency and reduce program execution time. Here method1 and method2 are unrelated, that is, method1 execution and method2 execution positions can be adjusted without affecting the execution of the program, could we execute the METHOD1 for thread 1 and then build the thread and execute the METHOD2? Because Method1 and method2 all need results, we need to use the callable interface and then use Future.get () to get the result of execution, but actually future.get () is blocked before the program returns the result, that is, Thread 1 When executing the Method1 method, the program waits here until Method1 returns the result result1 because the Future.get () is invoked, then thread 2 can execute METHOD2, likewise, Future.get () will also wait until the result of the METHOD2 result2 return, so that we open thread 1, open thread 2 does not get the effect of concurrent execution method1,method2, but because the program to open the thread and more occupy the program's execution time, The execution time of the program is time=time1+time2+time (thread opening time). So we get the transition state of the serial program.
Import Com.yang.domain.BaseResult;
Import Org.junit.Test;
Import Java.lang.reflect.Method;
Import java.util.concurrent.*; /** * @Description: * @Author: yangzl2008 * @Date: 2016/1/9 19:13/public class Serialcallable {@Test Publ IC void test01 () throws Exception {//Two threads thread pool Executorservice executorservice = Executors.newfixedthread
Pool (2);
Long start = System.currenttimemillis ();
Open thread execution future<baseresult> future1 = Executorservice.submit (This, "method1", null); Block until the program returns.
Time-consuming time1 baseresult baseResult1 = Future1.get ();
Open thread execution future<baseresult> future2 = Executorservice.submit (This, "method1", null); Block until the program returns.
Time-consuming time2 baseresult baseResult2 = Future2.get ();
Long end = System.currenttimemillis (); Total time elapsed = time1 + time2 + time (thread execution time consuming) System.out.println ("BASERESULT1 is" + BASERESULT1 + "\nbaseresult2 are " + BASERESULT2 + "\ntime cost is" + (End-start));
Public Baseresult method1 () {Baseresult baseresult = new Baseresult ();
try {TimeUnit.SECONDS.sleep (1);
catch (Interruptedexception e) {e.printstacktrace ();
} baseresult.setcode (1);
Baseresult.setmsg ("method1");
return baseresult;
Public Baseresult method2 () {Baseresult baseresult = new Baseresult ();
try {TimeUnit.SECONDS.sleep (1);
catch (Interruptedexception e) {e.printstacktrace ();
} baseresult.setcode (1);
Baseresult.setmsg ("Method2");
return baseresult;
Class Task<t> implements Callable<t> {Private Object object;
Private object[] args;
Private String methodname;
Public Task (Object object, String methodname, object[] args) {This.object = object; This.args = argS
This.methodname = methodname; @Override public T Call () throws Exception {Method method = Object.getclass (). GetMethod (Me
Thodname);
Return (T) Method.invoke (object, args); }
}
}Execution results:
BASERESULT1 is baseresult{code=1, msg= ' method1 '}
baseResult2 is baseresult{code=1, msg= ' method1 '}
2001
3. Parallel programThere is no way to execute the method1 at the same time the implementation of METHOD2, the final results are processed. We return to the source of the problem, the program first executed method1 get results result1, in the execution method2 get results result2, and then according to RESULT1 and RESULT2 results to determine the next step of the implementation of the program, Eventually we get the results of RESULT1 and RESULT2, and then we do the next step, so when we get result1 and result2, method1 and METHOD2 can actually execute concurrently, That is, I execute the method1 and then execute the MOTHOD2, I do not care about their return results, only when I want to take result1 and RESULT2 operation, the program will invoke the Future.get () method (this method will wait until the result returned), which is a
Deferred loadingof thought,
is consistent with the delay loading of properties in Hibernate, that is, for attribute A, I do not normally do not assign value, only when I am in use, execute SQL query to its assignment operation。 So, we get the concurrent execution of the program form.
Hibernate also uses Cglib to implement deferred loading, so we can consider using the Cglib delay loading class to parallel the serial program.
Import Com.yang.domain.BaseResult;
Import Net.sf.cglib.proxy.Enhancer;
Import Net.sf.cglib.proxy.LazyLoader;
Import Org.junit.Test;
Import Java.lang.reflect.Method;
Import java.util.concurrent.*; /** * @Description: * @Author: yangzl2008 * @Date: 2016/1/9 19:39/public class Parallel {@Test public voi
D test02 () throws Exception {Executorservice Executorservice = Executors.newfixedthreadpool (2);
Long start = System.currenttimemillis ();
Open thread execution future<baseresult> future1 = Executorservice.submit (This, "method1", null);
No blocking, normal execution, BASERESULT1 is a Cglib proxy class, using deferred loading, only when used to call the method to assign value.
Baseresult baseResult1 = Futuregetproxy (Future1, Baseresult.class);
Open thread execution future<baseresult> future2 = Executorservice.submit (This, "METHOD2", null);
No blocking, normal execution, BASERESULT1 is a Cglib proxy class, using deferred loading, only when used to call the method to assign value.
Baseresult baseResult2 = Futuregetproxy (Future2, Baseresult.class); Here you will use BASERESULT1 and BaseResult2 System.out.println ("BASERESULT1 is" + BASERESULT1 + "\NBASERESULT2 is" +
BASERESULT2);
Long end = System.currenttimemillis ();
Total time consuming = max (time1,time2) System.out.println ("Time Cost is" + (End-start)); Private <T> T Futuregetproxy (future<t> Future, Class clazz) {Enhancer enhancer = new Enhancer (
);
Enhancer.setsuperclass (Clazz);
Return (T) enhancer.create (Clazz, New Futurelazyloader (future));
/** * Deferred Load class * @param <T> * * Class Futurelazyloader<t> implements Lazyloader {
Private future<t> Future;
Public Futurelazyloader (future<t> Future) {this.future = Future;
@Override public Object Loadobject () throws Exception {return future.get ();
} public Baseresult method1 () {Baseresult baseresult = new Baseresult (); try {TimeUnit.SECONDS.sleep (1);
catch (Interruptedexception e) {e.printstacktrace ();
} baseresult.setcode (1);
Baseresult.setmsg ("method1");
return baseresult;
Public Baseresult method2 () {Baseresult baseresult = new Baseresult ();
try {TimeUnit.SECONDS.sleep (1);
catch (Interruptedexception e) {e.printstacktrace ();
} baseresult.setcode (1);
Baseresult.setmsg ("Method2");
return baseresult;
Class Task<t> implements Callable<t> {Private Object object;
Private object[] args;
Private String methodname;
Public Task (Object object, String methodname, object[] args) {This.object = object;
This.args = args;
This.methodname = methodname; @Override public T Call () throws Exception {Method method = objEct.getclass (). GetMethod (methodname);
Return (T) Method.invoke (object, args); }
}
}Execution results:
BASERESULT1 is baseresult{code=1, msg= ' method1 '}
baseResult2 is baseresult{code=1, msg= ' method2 '}
1057
4. ThinkingAbove, will method1,method2 separate new thread execution, finally obtains the result, then continues carries on the implementation to have many, in j.u.c Countdownlatch and Cyclicbarrier is can realize this kind of thought the typical tool class.
This article is just another way to come up with a solution, but for the process has been formed, that is, without changing the program code, the use of aop,cglib to achieve the parallelization of existing programs, this article is easier to implement the idea. Using spring's AOP implementation, you open the new line callable in the slice method to execute the method that is being proxied, and use cglib to delay loading the return value. 5, referenceCombat Cglib Series of Proxy (iii): delayed loading Lazyloader actual combat cglib implementation Aop-cglib
program source Download