Hi,

First of all sorry for my bad english :)
I need to implement a feature in my application, that will enable me to define the timeout of every request. I tried to create a Interceptor and put the main thread on wait, while other 2 threads, one will handle the time, and the other will make the invocation.invoke(). The first of this two threads to complete, will call the notify of the main thread and the correspondent result is returned.

I tried this approach, but i get a null pointer exception in the thread that tried to execute the invocation.invoke().

Is there any suggestions?

If some one need more explanations, please let me know.
You can find the code bellow.

Thanks in advance,
Jorge Sousa from Portugal

Code:

public class TimeoutInterceptor extends AbstractInterceptor {

private static final ExecutorService threadPool = Executors.newCachedThreadPool();

    @Override
    public String intercept(ActionInvocation invocation) throws Exception {
        Invocator invocator = new Invocator(invocation, this);
        TimeoutWatcher timeoutWatcher = new TimeoutWatcher(this);

        threadPool.execute(invocator);
        threadPool.execute(timeoutWatcher);

        this.wait();
        if (invocator.getResult().equalsIgnoreCase("running")) {
            throw new TimeOutException();
        } else {
            return invocator.getResult();
        }

    }

    private class TimeoutWatcher implements Runnable {

        private AbstractInterceptor abstractInterceptor;

        public TimeoutWatcher(AbstractInterceptor abstractInterceptor) {
            this.abstractInterceptor = abstractInterceptor;
        }

        @Override
        public void run() {
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
            }
            synchronized (abstractInterceptor) {
                abstractInterceptor.notify();
            }
        }
    }

    private class Invocator implements Runnable {

        private ActionInvocation invocation;
        private String result = "running";
        private AbstractInterceptor abstractInterceptor;

public Invocator(ActionInvocation invocation, AbstractInterceptor abstractInterceptor) {
            this.invocation = invocation;
            this.abstractInterceptor = abstractInterceptor;
        }

        @Override
        public void run() {
            try {
                result = invocation.invoke();
                synchronized (abstractInterceptor) {
                    abstractInterceptor.notify();
                }
            } catch (Exception e) {
                result = "error";
            }
        }

        public String getResult() {
            return result;
        }
    }

}





Reply via email to