Java Spring@Async与未来
我不熟悉java.util.concurrent.Future,有一些问题。如果我使用Future调用服务,我如何知道调用该服务时使用了什么元素 以下是一个例子:Java Spring@Async与未来,java,spring,asynchronous,future,Java,Spring,Asynchronous,Future,我不熟悉java.util.concurrent.Future,有一些问题。如果我使用Future调用服务,我如何知道调用该服务时使用了什么元素 以下是一个例子: 对于每个id,我使用java.util.concurrent.Future调用一个服务来填充一些额外的数据 Collection< Future< ObjectX>> future = new ArrayList< Future< ObjectX>>(); 谢谢大家! 这里有几件事
Collection< Future< ObjectX>> future = new ArrayList< Future< ObjectX>>();
谢谢大家! 这里有几件事你可以做
收藏未来的成为地图(地图)地图的关键应该是你可以用来映射回初始ObjectX
的一些方法
//to kick off the tasks
Map<ObjectX, Future<ObjectY>> futures = new HashMap<ObjectX, Future<ObjectY>>();
for (ObjectX id: ids)
{
futures.put(id, getAsyncInfo(id));
}
//...some time later...
//to fetch the results
for(Map.Entry<ObjectX, Future<ObjectY>> entry : futures.entrySet())
{
final ObjectX id = entry.getKey();
final Future<ObjectY> future = entry.getValue();
final ObjectY objY = future.get();
id.setResult(objY);
}
//启动任务
Map futures=newhashmap();
用于(ObjectX id:ids)
{
futures.put(id,getAsyncInfo(id));
}
//……过了一段时间。。。
//获取结果
for(Map.Entry:futures.entrySet())
{
final ObjectX id=entry.getKey();
最终未来=entry.getValue();
final ObjectY objY=future.get();
id.setResult(objY);
}
我会这样做
class MyResult extends AsyncResult<Object> {
Object id;
public MyResult(Object id, Object res) {
super(res);
this.id = id;
}
public Object getId() {
return id;
}
}
@Async
public MyResult getAsyncInfo(Object id) {
Object res = callService(id);
return new MyResult(id, res);
}
类MyResult扩展了AsyncResult{
对象id;
公共MyResult(对象id、对象res){
超级(res);
this.id=id;
}
公共对象getId(){
返回id;
}
}
@异步的
公共MyResult getAsyncInfo(对象id){
Object res=callService(id);
返回新的MyResult(id,res);
}
现在您知道result和id。id和result可能是任何类型的很抱歉,结果返回不同类型的object。1或2对回答您的问题有帮助吗?最后一段只是对我观察到的一些东西的评论(由于问题编辑后不再适用,因此被删除)。感谢您的回复
ids.get(0).setResult(serviceResult.get(0))????
ids.get(0).setResult(serviceResult.get(1))????
ids.get(0).setResult(serviceResult.get(2))????
...
//to kick off the tasks
Map<ObjectX, Future<ObjectY>> futures = new HashMap<ObjectX, Future<ObjectY>>();
for (ObjectX id: ids)
{
futures.put(id, getAsyncInfo(id));
}
//...some time later...
//to fetch the results
for(Map.Entry<ObjectX, Future<ObjectY>> entry : futures.entrySet())
{
final ObjectX id = entry.getKey();
final Future<ObjectY> future = entry.getValue();
final ObjectY objY = future.get();
id.setResult(objY);
}
class MyResult extends AsyncResult<Object> {
Object id;
public MyResult(Object id, Object res) {
super(res);
this.id = id;
}
public Object getId() {
return id;
}
}
@Async
public MyResult getAsyncInfo(Object id) {
Object res = callService(id);
return new MyResult(id, res);
}