steveohara / j2mod

Enhanced Modbus library implemented in the Java programming language
Apache License 2.0
265 stars 111 forks source link

Synchronized Connect and disconnect methods in ModbusTCPMaster #88

Closed ehsanjavadynia closed 5 years ago

ehsanjavadynia commented 5 years ago

Expected Behavior

ModbusTCPMaster connect and disconnect methods not to be synchronized

Actual Behavior

ModbusTCPMaster connect and disconnect are synchronized

Specifications

We want to use j2mod modbus in a servlet. But the problem is that the connect and disconnect methods are synchronized and they degrade our servlet performance.

/**
     * Connects this <tt>ModbusTCPMaster</tt> with the slave.
     *
     * @param useRtuOverTcp True if the RTU protocol should be used over TCP
     *
     * @throws Exception if the connection cannot be established.
     */
    public synchronized void connect(boolean useRtuOverTcp) throws Exception {
        if (connection != null && !connection.isConnected()) {
            connection.connect(useRtuOverTcp);
            transaction = connection.getModbusTransport().createTransaction();
            ((ModbusTCPTransaction)transaction).setReconnecting(reconnecting);
            setTransaction(transaction);
        }
    }

Is it possible for us to make connect and disconnect methods asynchronous(if we make a new connection handler and a modbus master class on each servlet call)?

steveohara commented 5 years ago

I will look at a better way of synchronising the open/close mechanism on a connection but can I suggest you also look at another strategy in your code. Opening/closing connections is expensive, in high performance systems you should really look to mitigate this by cacheing connections and re-using them.

steveohara commented 5 years ago

I've come to the conclusion that in most cases, the library is being overly aggressive with regards to synchronisation and it is hurting performance. So I have removed a number of synchronized decorators including the ones mentioned in this ticket.