您的位置:首页 > 编程语言 > Java开发

JAVA Callback效率测试

2015-09-19 00:00 691 查看
摘要: JAVA Callback效率测试

在最近的联网电商项目中,想要实现单个web容器内的支付请求,全部能够统一宏观上同步,实现粒度上面异步,找来找去,没有相关方面的框架或者方案,于是最后基于现实场景,打算使用Java callback 的多线程方式,假象伪并发量为100000

/**
*
* @author gyx
*
*/
public class A
{
private double id = 0;
public A(double id)
{
this.setId(id);
}
public double getId()
{
return id;
}
public void setId(double id)
{
this.id = id;
}

/**
* 线程类
* @author gyx
*
*/
public class MyCallable implements Callable<A>
{
private A obj;

/**
* 线程类构造函数,传入线程序号
* @param taskNum
*/
public MyCallable(A obj)
{
this.setObj(obj);
}

/**
* 重写接口的方法,子线程调用 <br/>
* 此方法是生成0-99的数字,(百位表示子线程序号)用list返回
*/
public A call() throws Exception
{
Date dateTmp1 = new Date();
System.out.println("business_start.............and------begin" + this.getObj().getId());
this.getObj().setId(Math.random() * 1000000000);
Date dateTmp2 = new Date();
long time = dateTmp2.getTime() - dateTmp1.getTime();
System.out.println("线程" + Thread.currentThread().getId() + "任务时间【" + time + "毫秒】");
return this.getObj();
}

public A getObj()
{
return obj;
}

public void setObj(A obj)
{
this.obj = obj;
}

/**
* @author gyx
*主线程调用
*/
public class Test
{
public static void main(String[] args) throws InterruptedException, ExecutionException
{
try
{
System.out.println("----程序开始运行----");
Date date1 = new Date();
int taskSize = 100000;
// 创建一个线程池
// ExecutorService pool = Executors.newFixedThreadPool(4);
ExecutorService pool = Executors.newCachedThreadPool();
// 创建多个有返回值的任务
List<Future<A>> list = new ArrayList<Future<A>>();
for (int i = 0; i < taskSize; i++)
{
System.out.println("the current is ............" + i);
Callable<com.athena.ckx.module.transTime.A> c = new MyCallable(new A(0));
// 执行任务并获取Future对象
Future<A> f = pool.submit(c);
System.out.println("get-result----------------------" + f.get().getId());
list.add(f);
}
// 关闭线程池
pool.shutdown();
Date date2 = new Date();
System.out.println("----程序结束运行----,程序运行时间【" + (date2.getTime() - date1.getTime()) + "毫秒】");
// 获取所有并发任务的运行结果
// for (Future<A> f : list)
// {
// // 从Future对象上获取任务的返回值,并输出到控制台
// System.out.println("get-result----------------------" + f.get().getId());
// }
}
catch(Exception e)
{
e.printStackTrace();
System.exit(0);
}
finally
{
System.exit(0);
}
}
}

结果为:----程序结束运行----,程序运行时间【26351毫秒】

调整线程池:

ExecutorService pool = Executors.newFixedThreadPool(2);

结果为:----程序结束运行----,程序运行时间【17128毫秒】

调整线程池:

ExecutorService pool = Executors.newFixedThreadPool(1);

结果为:程序运行时间【16269毫秒】

结论:newCachedThreadPool 效率最差,线程数小于cpuh核心 2/1 效率相对高,代价也比较平稳,处理当下假想,基本满足要求。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: