Olá,
Estou com uma dificuldade meio besta aqui. Preciso implementar um timeout em um método, a execução tem que se interrompida se o método nãor etornar em X segundos.
A solução que pensei foi criar um Command rodando em outra thread e ir checando um atributo que indica se o processamento terminou, mas acho que isso é meio idiota… deve ter um jeito mais simples =/
Segue o código + ou - que estou usando:
//Classe que coordena os requests
public clas Coordena{
public Subscriber getSubscriber(String string) throws BonusSystemException,
BlockedTariffIdException {
Subscriber subscriber = null;
//prepares the thrreaded request and fires it
GetSubscriberCommand request = new GetSubscriberCommand(string, system);
request.execute();
while (request.isProcessing()) {
//Decrease the time we will use to sleep
availableTime -= SLEEP_TIME;
//If still have some time, sleeps
if (availableTime > 0)
try {
sleep(SLEEP_TIME);
} catch (InterruptedException e) {
throw new BonusSystemException(e);
}
}
checkRequestStatus(request);
return request.getResponse();
}
private void checkRequestStatus(GetSubscriberCommand request) throws BonusSystemException, BlockedTariffIdException {
int operationStatus = request.getStatus();
if (operationStatus != GetSubscriberCommand.SUCCESS) {
switch (operationStatus) {
case GetSubscriberCommand.ERROR:
throw (BonusSystemException) request.getException();
case GetSubscriberCommand.BLOCKED:
throw (BlockedTariffIdException) request.getException();
}
}
}
}
Note que o processamento pode gerar dois tipos de exceção, mas como a thread não pode me retorná-las diretamente, estou usando um código de erro ( :evil: ). A classe command é esta:
class GetSubscriberCommand extends Thread {
private BonusSystem bonusSystem = null;
private String msisdn = null;
private Subscriber response = null;
private boolean processing = false;
private int status = SUCCESS;
public static final int SUCCESS = 0;
public static final int ERROR = 1;
public static final int BLOCKED = 2;
private Exception exception = null;
public boolean isProcessing() {
return processing;
}
public void execute() {
processing = true;
try {
response=bonusSystem.getSubscriber(null, msisdn);
} catch (BonusSystemException e) {
status = ERROR;
exception = e;
} catch (BlockedTariffIdException e) {
status = BLOCKED;
exception = e;
}
processing = false;
}
//getters and setters
}
Alguém tem alguma idéia menos gortesca? É apenas uma operação numa das 3 interfaces do sistema que não pdoe demorar tanto, a solução teria que ser bem simples 
[]s