java – 为什么matlabcontrol在代理创建时中断调用线程?

前端之家收集整理的这篇文章主要介绍了java – 为什么matlabcontrol在代理创建时中断调用线程?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我让我的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;
        }
    }
}
原文链接:https://www.f2er.com/java/129148.html

猜你在找的Java相关文章