Hi have problems with an asynchronous method call in JBoss 6.0 Final.
The classes look like the following:
One is just some kind of storage which contains a number of objects.
@Singleton
public class Storage {
private Map<Integer, Object> storage = new HashMap<Integer, Object>();
@Asynchronous
public Future<Object> getAsync(int id) {
Object obj = null;
while (null == obj ) {
obj = storage .remove(id);
}
return new AsyncResult<Object>(obj);
}
public void add(int id, Object obj) {
storage.put(id, obj(
}
}
Then there is a class that processes something and tries to find an object out of the storage with a given id. It should wait a specified time of it can find an object for this id out of the storage. If there is nothing, stop searching for it and go on:
@Singleton
public class Executor {
@Inject
private Storage storage;
public void execute(int id) {
Future<Object> fut = storage.getAsync(id);
Object obj;
try {
obj = t.get(30L, TimeUnit.SECONDS);
// go on processing of obj is found
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (TimeoutException e) {
//no object can be found.
// but we never reach this place
}
}
}
It can happen that there is no Object for the given ID in the storage, so the loop in the getAsync() Method is 'infinite'. That's why the TimeoutException should be thrown after 30 seconds. Interesting is, that the TimeoutException is never thrown.
Am I missing a point like don't make an 'infinite' loop in the asynchronous method?
UPDATE:
When I do a similar thing on a standalone application it's working properly:
public class Test {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(10);
Callable<Object> task = new Callable<Object>() {
public Object call() {
int i = 0;
while(i == 0) {
i = 0;
}
return null;
}
};
Future<Object> future = executor.submit(task);
try {
Object result = future.get(5, TimeUnit.SECONDS);
} catch (TimeoutException ex) {
ex.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
So basically doing an infinite loop in the asynchronous method is okay because in the standalone the TimeoutException catch block is called!
UPDATE II
When I replace the getAsync()
method with something similar to this, the get()
returns successfully without throwing the TimeoutException. But that's what I would expect to happen!
@Asynchronous
public Future<Telegram> getTelegramAsync(int telegramId) {
Telegram tlgrm = null;
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return new AsyncResult<Telegram>(tlgrm);
}
Any help would be appreciated!
regards