java高併發的異步【非阻塞】

高併發系統中,性能上要求處理時間夠短,因此傳統阻塞式開發(一個線程內一行行代碼,一個個方法的順序執行,直到完成)明顯是不符合要求的,那麼必須作到非阻塞式。如何來作:java

 咱們能選擇的方式通常以下:併發

    

1,同步阻塞調用異步

即串行調用,耗時爲全部服務的耗時總和高併發

2,半異步(異步Future)性能

線程池,異步Future,總耗時爲最長響應時間;比起阻塞調用可以下降總響應時間,可是阻塞主請求線程,高併發時依然會形成線程數過多,CPU上下文切換spa

 

他們分別如何實現:線程

1,同步阻塞調用code

import java.util.Map;

public class Test1 {
	public static void main(String[] args) throws Exception {
		RpcService rpcService = new RpcService();
		HttpService httpService = new HttpService();
		long t1=System.currentTimeMillis();
		// 耗時  10  ms
		Map<String, String> result1 = rpcService.getRpcResult();
		// 耗時 20 ms
		Integer result2 = httpService.getHttpResult();
		// 總耗時 10+20 ms
		long t2=System.currentTimeMillis();
		System.out.println(t2-t1);
	}

	static class RpcService {
		Map<String, String> getRpcResult() throws Exception {
			// 調用遠程方法(遠程方法耗時約10ms,能夠使用Thread.sleep模擬)
			Thread.sleep(10);
			return null;
		}
	}

	static class HttpService {
		Integer getHttpResult() throws Exception {
			// 調用遠程方法(遠程方法耗時約20ms,能夠使用Thread.sleep模擬)
			Thread.sleep(20);
			return 0;
		}
	}
}

2,半異步(異步Future)開發

import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

public class Test {
	final static ExecutorService executor = Executors.newFixedThreadPool(2);

	public static void main(String[] args) {
		final RpcService rpcService = new RpcService();
		final HttpService httpService = new HttpService();
		Future<Map<String, String>> future1 = null;
		Future<Integer> future2 = null;
		try {
			future1 = executor.submit(new Callable<Map<String, String>>() {
				public Map<String, String> call() throws Exception {
					return rpcService.getRpcResult();
				}
			});
			future2 = executor.submit(new Callable<Integer>() {
				public Integer call()throws Exception  {
					return httpService.getHttpResult();
				}
			});
			long t1=System.currentTimeMillis();
			// 耗時 10 ms
			Map<String, String> result1 = future1.get(300,
					TimeUnit.MILLISECONDS);
			// 耗時 20 ms
			Integer result2 = future2.get(300, TimeUnit.MILLISECONDS);
			long t2=System.currentTimeMillis();
			// 總耗時 20 ms
			System.out.println(t2-t1);
			executor.shutdown();
		} catch (Exception e) {
			if (future1 != null) {
				future1.cancel(true);
			}
			if (future2 != null) {
				future2.cancel(true);
			}
			throw new RuntimeException(e);
		}
	}

	static class RpcService {
		Map<String, String> getRpcResult() throws Exception {
			// 調用遠程方法(遠程方法耗時約10ms,能夠使用Thread.sleep模擬)
			Thread.sleep(10);
			return null;
		}
	}

	static class HttpService {
		Integer getHttpResult() throws Exception {
			// 調用遠程方法(遠程方法耗時約20ms,能夠使用Thread.sleep模擬)
			Thread.sleep(20);
			return 0;
		}
	}
}

其餘的方式待續。。。。。。rpc

相關文章
相關標籤/搜索