1. 程式人生 > 其它 >Guava非同步回撥任務

Guava非同步回撥任務

說明

Guava主要增強了Java而不是另起爐灶。
Guava的FutureCallback與Java的Callable名字相近,實質不同,存在本質的區別:

  1. Java的Callable介面代表的是非同步執行的邏輯。
  2. Guava的FutureCallback介面代表的是Callable非同步邏輯執行完成之後,根據成功或者異常兩種情形所需要執行的善後工作。

Guava執行緒池是對Java執行緒池的一種裝飾。

Guava非同步回撥的流程如下:

  1. 實現Java的Callable介面,建立非同步執行邏輯。還有一種情況,如果不需要返回值,非同步執行邏輯也可以實現Runnable介面。
  2. 建立Guava執行緒池。
  3. 將第1步建立的Callable/Runnable非同步執行邏輯的例項提交到Guava執行緒池,從而獲取ListenableFuture非同步任務例項。
  4. 建立FutureCallback回撥例項,通過Futures.addCallback將回調例項繫結到ListenableFuture非同步任務上。

程式碼示例

package syb.test.busi;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.LockSupport;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;

@Component
public class Sample {
	private Logger logger = LoggerFactory.getLogger(getClass());

	public void test() throws Exception {
		// 建立Callable例項
		Callable<String> callable = () -> {
			logger.info("callable start");
			LockSupport.parkNanos(1L * 1000 * 1000 * 1000);
			logger.info("callable end");
			return "abc";
		};
		
		// 建立java執行緒池,用於執行callable任務
		ExecutorService jpool = new ThreadPoolExecutor(1, 1, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<>(10), new ThreadFactory() {
			
			@Override
			public Thread newThread(Runnable r) {
				Thread t = new Thread(r);
				t.setName("T-Callable");
				return t;
			}
		}, new ThreadPoolExecutor.AbortPolicy());
		
		// 建立guava執行緒池
		ListeningExecutorService gpool = MoreExecutors.listeningDecorator(jpool);
		
		// 提交任務,獲得ListenableFuture
		ListenableFuture<String> listenableFuture = gpool.submit(callable);
		
		// 建立執行緒池,用於執行回撥函式
		ExecutorService jpoolCallback = new ThreadPoolExecutor(1, 1, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<>(10), new ThreadFactory() {
			
			@Override
			public Thread newThread(Runnable r) {
				Thread t = new Thread(r);
				t.setName("T-Callback");
				return t;
			}
		}, new ThreadPoolExecutor.AbortPolicy());
		
		// 將listenableFuture與FutureCallback關聯
		Futures.addCallback(listenableFuture, new FutureCallback<String>() {

			@Override
			public void onSuccess(String result) {
				logger.info("callable execute success, result: {}", result);
			}

			@Override
			public void onFailure(Throwable t) {
				logger.error("callable execute failure, {}", t);
			}
		}, jpoolCallback);
	}
}

--結束--