2014-12-10 21 views
7

Tôi đã làm cho chuỗi điều khiển Matlab của tôi bị gián đoạn và phát hiện thấy rằng nó bị gián đoạn tất cả thời gian trong lần chạy đầu tiên.Tại sao matlabcontrol ngắt chuỗi gọi khi proxy tạo ra?

Điều này là do GetProxyRequestCallback có gián đoạn code bên trong:

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; 
    } 
} 

Có bất kỳ lý do để ngắt gọi chủ đề hay đây chỉ là một lỗi?

Trả lời

0

Phương thức RemoteMatlabProxyFactory.getProxy() tạo một phiên bản GetProxyRequestCallback và sau đó ngủ, chờ phương thức proxyCreated(...) được gọi. Do đó, nếu proxyCreated() không làm gián đoạn luồng mà ban đầu đã tạo yêu cầu, chuỗi này sẽ đợi cho đến khi hết thời gian chờ. Theo tôi, đây là một lỗ hổng trong thư viện matlabcontrol: Thread.interrupt() không nên bị lạm dụng vì mục đích này vì một thread bị gián đoạn có thể có các lý do khác nhau và không nên được sử dụng cho bất cứ điều gì ngoại trừ báo hiệu rằng thread nên dừng lại.

Điều này phải được sửa trong thư viện matlabcontrol bằng cách chờ trên mutex thay thế.

Ví dụ:

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; 
     } 
    } 
} 
Các vấn đề liên quan