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

相关文章
相关标签/搜索