Java 1.4 timeout implementation

I cannot use Executor and Future to catch a TimeOutException, since it's 1.4. I need a timeout after 30 seconds if the method is not completed.

//Caller class public static void main() { EJBMethod() // has to timeout after 30 seconds } //EJB method in some other class public void EJBMethod() { } 

An approach that I think is to wrap this method call in Runnable and set some volatile boolean from run () after the method finishes. THEN, in the caller, we can sleep for 30 seconds after calling this method and after he wakes up, I will check the logical value in the caller, if it is installed. If not set, we need to stop this thread.

+4
source share
1 answer

In the simplest case, you can just go with Thread + an arbitrary Runnable.

If you want to block the call from the perspective of the caller, you can create a β€œservice” class that starts the worker thread and uses Thread. join (long) to wait for the operation to complete or to refuse it after the specified timeout (pay special attention to the correct handling of InterruptedException so that everything is not confused).

Thread.isAlive () will tell you whether Thread was completed or not.

Getting the result is a separate issue; I think you can handle this ...

[EDIT]

A quick and dirty example ( do not use in the production process as it is! ):

 /** * Actually needs some refactoring * Also, did not verify for atomicity - should be redesigned */ public V theServiceCall(final T param) { final MyResultBuffer<V> buffer = new MyResultBuffer<V>(); Runnable task = new Runnable() { public void run() { V result = ejb.process(param); buffer.putResult(result); } } Thread t = new Thread(task); t.setDaemon(true); t.start(); try { t.join(TASK_TIMEOUT_MILLIS); } catch (InterruptedException e) { // Handle it as needed (current thread is probably asked to terminate) } return (t.isAlive()) ? null : buffer.getResult(); } 

NOTE. Instead of Thread.setDaemon (), you can implement the shutdown flag in your Runnable, as that would be a better solution.

[/ EDIT]

+2
source

All Articles