stepfunc / rodbus

Rust implementation of Modbus with idiomatic bindings for C, C++, .NET, and Java
https://stepfunc.io/products/libraries/modbus/
Other
80 stars 22 forks source link

Java runtime reference #125

Open delawr0190 opened 9 months ago

delawr0190 commented 9 months ago

Assuming I'm using the java library correctly, I believe there's either a missing Runtime reference hold or the documentation may need to be updated to reflect how Runtime should be treated.

In my multi-threaded use of the library:

        final RuntimeConfig runtimeConfig =
                new RuntimeConfig()
                        .withNumCoreThreads(ushort(4));
        final Runtime runtime = new Runtime(runtimeConfig);
        this.channel =
                ClientChannel.createTcp(
                        runtime,
                        ip,
                        ushort(port),
                        ushort(1),
                        new RetryStrategy(),
                        DecodeLevel.nothing(),
                        state -> LOG.warn("State change: {}", state));
        this.channel.enable();

A separate scheduled executor periodically initiates reads from the channel.

With nothing holding the runtime reference, the gc seems to prune it, calling finalize(), which shuts down the Runtime and "SHUTDOWN" exceptions start to get thrown.

To fix this, holding the reference to Runtime on the class keeps the gc from deleting it, which keeps things going.

Couldn't find reference to this anywhere, so wanted to share. Unsure if intended or not.

jadamcrain commented 9 months ago

Hi @delawr0190. This is the expected behavior, although I think we should have an explicit warning about holding onto a reference to runtime until you're done here:

https://docs.stepfunc.io/rodbus/1.3.1/guide/docs/api/runtime#examples

We kind of hint about how the garbage collection interacts with this in the shutdown section, but I think calling it out explicitly for Java/C# in the section above would be better.

https://docs.stepfunc.io/rodbus/1.3.1/guide/docs/api/runtime#shutdown

jadamcrain commented 9 months ago

Leaving this open until the next release so we can update docs.