1 8 package examples.callback; 9 10 import org.codehaus.aspectwerkz.joinpoint.StaticJoinPoint; 11 import org.codehaus.aspectwerkz.annotation.Around; 12 13 import java.util.concurrent.Executor ; 14 import java.util.concurrent.Executors ; 15 import java.util.concurrent.ThreadFactory ; 16 17 29 public class Callback { 30 31 34 public void callback(String message) { 35 System.out.println("Callback.callback " + message); 36 } 37 38 43 public void work() { 44 System.out.println("Callback.work - start"); 45 Callee callee = new Callee(); 46 callee.longOp(10000); 47 System.out.println("Callback.work - end"); 48 } 49 50 56 public static void main(String args[]) throws Throwable { 57 Callback caller = new Callback(); 58 caller.work(); 59 } 60 61 64 public static class Callee { 65 66 public void longOp(int howLong) { 67 System.out.println("Callback$Callee.longOp for " + howLong); 68 for (int i = 0; i < howLong; i++) { 69 ; 70 } 71 } 72 } 73 74 public static class AsyncAspect { 75 76 79 private Executor m_threadPool = Executors.newCachedThreadPool( 80 new ThreadFactory () { 81 public Thread newThread(Runnable target) { 82 Thread t = new Thread (target); 83 t.setDaemon(true); return t; 85 } 86 } 87 ); 88 89 @Around("call(* *..*.*Callee.longOp(int)) && args(howLong) && this(caller)") 91 public Object doAsync(final StaticJoinPoint sjp, int howLong, final Callback caller) throws Throwable { 92 System.out.println("[AOP powered] - Callback$AsyncAspect.doAsync - for this long: " + howLong); 93 m_threadPool.execute( 94 new Runnable () { 95 public void run() { 96 try { 97 sjp.proceed(); 99 caller.callback( 101 "[AOP powered] - I am done there .. " + Thread.currentThread().getName() 102 ); 103 } catch (Throwable e) { 104 throw new RuntimeException (e); 105 } 106 } 107 } 108 ); 109 return null; 110 } 111 } 112 113 114 } 115 | Popular Tags |