apache / plc4x

PLC4X The Industrial IoT adapter

Home Page:https://plc4x.apache.org/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

[Bug]: LeasedPlcConnection has thread safety issues

flywithrain opened this issue · comments

What happened?

HI, the connection in LeasedPlcConnection will be closed by Timer schedule or public medthod "close()" called. How to ensure the connection is not null when other thread call?

Version

develop

Programming Languages

  • plc4j
  • plc4go
  • plc4c
  • plc4net

Protocols

  • AB-Ethernet
  • ADS /AMS
  • BACnet/IP
  • CANopen
  • DeltaV
  • DF1
  • EtherNet/IP
  • Firmata
  • KNXnet/IP
  • Modbus
  • OPC-UA
  • S7

Having a look at the code, the only method where this could be a problem is the "close()" method itself. All others check if connection is != null before doing anything. But indeed, this might result in problems when double-closing a connection (Nothing popped my eye when reviewing it however). I'll add an additional check to that method, just to be on the safe side.

I also took the liberty to change the code to use an AtomicReference instead of the unsynchronized variable access.

I'm sorry. Due to some reasons, I didn't describe it clearly before. My concerns are as follows
Thread A:

// step 1
PlcConnection con = cachedPlcConnectionManager.getConnection();
// step 2
PlcWriteRequest writeRequest = con.writeRequestBuilder().build();
// step 5
PlcWriteResponse writeResponse = writeRequest.execute().get();

Thread B:

// step 3
PlcConnection con = cachedPlcConnectionManager.getConnection();
// step 4
con.close();

When executing step 5 the "writer" in method execute() actually is the old 'con' which closed by thread B in step 4, that will cause the write fail.
Maybe the method close() can wait other thread write finish or use the new connection to do write?
@chrisdutz