digitalpetri / modbus

Modbus TCP, Modbus RTU/TCP, and Modbus RTU/Serial for Java 17+.
Eclipse Public License 2.0
653 stars 222 forks source link

Should I invoke the close() function of the ModbusTcpMaster instance when my collection task finished ? #51

Closed MengMengDaXiaoJi closed 1 year ago

MengMengDaXiaoJi commented 1 year ago

My program occurred a terrible memory leak problem without invoking the close() function of the ModbusTcpMaster instance. Should I invoke the close() function of the ModbusTcpMaster instance to solve this problem?

By the way, I found it really use much time to invoke Modbus.releaseSharedResources() function compared with no invoking it.

MengMengDaXiaoJi commented 1 year ago
        future.whenCompleteAsync((result, throwable) -> {
            modbusMasterUtil.disposeModbusConnector();
            if (throwable != null) {
                future.completeExceptionally(throwable);
            }
        });

        public void disposeModbusConnector() {
            if (modbusMaster != null) {
                modbusMaster.disconnect();
            }
      //        Modbus.releaseSharedResources();
        }

This memory leak problem seems to be solved by add this code.

kevinherron commented 1 year ago

releaseSharedResources should only be called when you are done using the library, usually during application shutdown or something like that.

The memory leak could be from responses that did not have their buffers released as the example in the README shows.

Calling ModbusTcpMaster::disconnect should be done if you aren't planning to use that master instance any more, otherwise it may still be "alive" and trying to maintain a connection.

MengMengDaXiaoJi commented 1 year ago

Thank you for your answer, it really solved my long-standing confusion.

releaseSharedResources should only be called when you are done using the library, usually during application shutdown or something like that.

The memory leak could be from responses that did not have their buffers released as the example in the README shows.

Calling ModbusTcpMaster::disconnect should be done if you aren't planning to use that master instance any more, otherwise it may still be "alive" and trying to maintain a connection.