我让我的Matlab控制线程可以中断,并发现它在第一次运行时一直被中断.
这是因为GetProxyRequestCallback内部有中断代码:
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; } }
解决方法
RemoteMatlabProxyFactory.getProxy()方法创建一个GetProxyRequestCallback实例,然后休眠,等待调用proxyCreated(…)方法.因此,如果proxyCreated()没有中断最初创建请求的线程,则此线程将等待直到达到超时.
在我看来,这是matlabcontrol库中的一个缺陷:Thread.interrupt()不应该被滥用于此目的,因为被中断的线程可能有不同的原因,不应该用于除线程应该停止的信号之外的任何事情.
这应该通过等待互斥锁来修复matlabcontrol库中的问题.
例如:
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; } } }