7

I made my Matlab controlling thread interruptable and found, that it is interrupted all the time on first run.

This is because GetProxyRequestCallback has interrupting code inside:

private static class GetProxyRequestCallback implements RequestCallback
{
    private final Thread _requestingThread;
    private volatile MatlabProxy _proxy;

    public GetProxyRequestCallback()
    {
        _requestingThread = Thread.currentThread();
    }

    @Override
    public void proxyCreated(MatlabProxy proxy)
    {
        _proxy = proxy;

        _requestingThread.interrupt();
    }

    public MatlabProxy getProxy()
    {
        return _proxy;
    }
}

Are there any reasons to interrupt calling thread or this is just a bug?

Suzan Cioc
  • 29,281
  • 63
  • 213
  • 385

1 Answers1

0

The RemoteMatlabProxyFactory.getProxy() method creates an instance of GetProxyRequestCallback and then sleeps, waiting for the proxyCreated(...) method to be called. Therefore, if proxyCreated() did not interrupt the thread that originally created the request, this thread would wait until the timeout would be reached.

In my opinion, this is a flaw in the matlabcontrol library: Thread.interrupt() should not be abused for this purpose because a thread being interrupted can have different reasons and should not be used for anything except signaling that the thread should stop.

This should be fixed in the matlabcontrol library by waiting on a mutex instead.

For example:

class RemoteMatlabProxyFactory implements ProxyFactory {
    // [...]

    @Override
    public MatlabProxy getProxy() throws MatlabConnectionException {
        GetProxyRequestCallback callback = new GetProxyRequestCallback();
        Request request = this.requestProxy(callback);
        return callback.getProxy(_options.getProxyTimeout());
    }

    // [...]
}

private static class GetProxyRequestCallback implements RequestCallback {
    private final Object _lock = new Object();
    private MatlabProxy _proxy;

    @Override
    public void proxyCreated(MatlabProxy proxy) {
        _proxy = proxy;

        _requestingThread.interrupt();
    }

    public MatlabProxy getProxy(long timeout) throws MatlabConnectionException {
        synchronized (_lock) {
            if (_proxy != null) {
                return _proxy;
            }
            try {
                _lock.wait(timeout);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                throw new MatlabConnectionException("Thread was interrupted while waiting for MATLAB proxy", e);
            }
            if (_proxy == null) {
                throw new MatlabConnectionException("MATLAB proxy could not be created in " + timeout + " milliseconds");
            }
            return _proxy;
        }
    }
}