CompletableFuture集合threadPool来提高并发处理

CompleteableFuture基于jdk8。提高程序吞吐量,异步处理请求。

public class Shop {
	
	Random random = new Random();
	
	private String name;
	
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Shop(String name) {
		super();
		this.name = name;
	}

	public static void delay() {
		try {
			Thread.sleep(1000L);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	
	public double getPrice(String product) {
		delay();
		return random.nextDouble() * 100;
	}
	
//	public Future<Double> getPriceAsync(String product){
//		CompletableFuture<Double> futurePrice = new CompletableFuture<>();
//		new Thread(()->futurePrice.complete(getPrice(product))).start();
//		return futurePrice;
//	}
	/**推荐使用这种方式
	 * 1.将getPrice()方法转为异步调用。
	 * 2.supplyAsync参数是一个生产者。Supplier 没有参数返回一个对象。若lambda没有参数并且可以返回对象则满足
	 * 3.supplyAsync内部对Supplier方法对异常进行处理,避免因为异常程序永久阻塞。
	 * */
	public Future<Double> getPriceAsync(String product){
		return CompletableFuture.supplyAsync(()->getPrice(product));
	}
	
	public static void main(String[] args) throws Exception{
		Shop shop = new Shop("bestShop");
		long start = System.currentTimeMillis();
		Future<Double> futurePrice = shop.getPriceAsync("some product");
		System.out.println("调用返回,耗时"+(System.currentTimeMillis() - start));
		double price = futurePrice.get();
		System.out.println("价格返回,耗时"+(System.currentTimeMillis() - start));
	}
}

2.我们在此基础上升级:

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

public class PriceDemo {
	
	private List<Shop> shops = Arrays.asList(new Shop("shop1"),
			new Shop("shop2"),
			new Shop("shop3"),
			new Shop("shop4"),
			new Shop("shop5"),
			new Shop("shop6"),
			new Shop("shop7"),
			new Shop("shop8"),
			new Shop("shop9"),
			new Shop("shop10"),
			new Shop("shop12"),
			new Shop("shop12"),
			new Shop("shop13"),
			new Shop("shop14"),
			new Shop("shop15"),
			new Shop("shop16"),
			new Shop("shop17"),
			new Shop("shop18"));
	
	public List<String> findPrices(String product){
		return shops.stream().parallel().map(shop->
		String.format("%s price is %.2f", shop.getName(), shop.getPrice(product)))
				.collect(Collectors.toList());
	}
	
//	public List<String> findPrice(String product){
//		List<CompletableFuture<String>> priceFuture = shops.stream()
//				.map(shop -> CompletableFuture
//						.supplyAsync(()-> String.format("%s price is %.2f", shop.getName(), shop.getPrice(product))))
//				.collect(Collectors.toList());
//		return priceFuture.stream().map(CompletableFuture::join).collect(Collectors.toList());
//	}
	
	public List<String> findPriceExecutorsCompletableFuture(String product){
		Executor executor = Executors.newFixedThreadPool(Math.min(shops.size(), 100));
		List<CompletableFuture<String>> priceFuture = shops.stream()
				.map(shop -> CompletableFuture
						.supplyAsync(()-> String.format("%s price is %.2f", shop.getName(), shop.getPrice(product)), executor))
				.collect(Collectors.toList());
		return priceFuture.stream().map(CompletableFuture::join).collect(Collectors.toList());
	}
	
	
	public static void main(String[] args) {
		PriceDemo priceDemo = new PriceDemo();
		long start = System.currentTimeMillis();
		System.out.println(priceDemo.findPrices("iphone 7"));
		System.out.println("服务耗时:"+(System.currentTimeMillis()-start));
		
		start = System.currentTimeMillis();
		System.out.println(priceDemo.findPriceExecutorsCompletableFuture("iphone 7"));
		System.out.println("服务耗时:"+(System.currentTimeMillis()-start));
	}
}

我们发现threadPool结合CompletableFuture可以大大的提高性能。项目中哪些地方可以用到哪?

  • 3
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 8
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值