Skip to content

Commit 339785a

Browse files
authored
Allow subclasses to provide a TransactionSequence (#89)
Refactor to use subclassing instead of a constructor parameter for customizing the TransactionSequence.
1 parent a978cb4 commit 339785a

File tree

1 file changed

+18
-12
lines changed

1 file changed

+18
-12
lines changed

modbus/src/main/java/com/digitalpetri/modbus/client/ModbusTcpClient.java

Lines changed: 18 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -35,25 +35,16 @@ public class ModbusTcpClient extends ModbusClient {
3535

3636
private final Map<Integer, ResponsePromise> promises = new ConcurrentHashMap<>();
3737

38+
private final AtomicReference<TransactionSequence> transactionSequence = new AtomicReference<>();
39+
3840
private final ModbusClientConfig config;
3941
private final ModbusTcpClientTransport transport;
40-
private final TransactionSequence transactionSequence;
4142

4243
public ModbusTcpClient(ModbusClientConfig config, ModbusTcpClientTransport transport) {
43-
this(config, transport, new DefaultTransactionSequence());
44-
}
45-
46-
public ModbusTcpClient(
47-
ModbusClientConfig config,
48-
ModbusTcpClientTransport transport,
49-
TransactionSequence transactionSequence
50-
) {
51-
5244
super(transport);
5345

5446
this.config = config;
5547
this.transport = transport;
56-
this.transactionSequence = transactionSequence;
5748

5849
transport.receive(this::onFrameReceived);
5950
}
@@ -116,7 +107,10 @@ public CompletionStage<ModbusResponsePdu> sendAsync(int unitId, ModbusRequestPdu
116107
}
117108

118109
private CompletionStage<ByteBuffer> sendBufferAsync(int unitId, ByteBuffer buffer) {
119-
int transactionId = transactionSequence.next();
110+
TransactionSequence sequence = transactionSequence.updateAndGet(
111+
ts -> ts != null ? ts : createTransactionSequence()
112+
);
113+
int transactionId = sequence.next();
120114

121115
var header = new MbapHeader(
122116
transactionId,
@@ -189,6 +183,16 @@ private void onFrameReceived(ModbusTcpFrame frame) {
189183
}
190184
}
191185

186+
/**
187+
* Create and return the {@link TransactionSequence} that will be used to generate transaction
188+
* ids.
189+
*
190+
* @return the {@link TransactionSequence} that will be used to generate transaction ids.
191+
*/
192+
protected TransactionSequence createTransactionSequence() {
193+
return new DefaultTransactionSequence();
194+
}
195+
192196
/**
193197
* Create a new {@link ModbusTcpClient} using the given {@link ModbusTcpClientTransport} and a
194198
* {@link ModbusClientConfig} with the default values.
@@ -239,6 +243,8 @@ public interface TransactionSequence {
239243
/**
240244
* Return the next 2-byte transaction identifier. Range is [0, 65535] by default.
241245
*
246+
* <p>Implementations must be safe for use by multiple threads.
247+
*
242248
* @return the next 2-byte transaction identifier.
243249
*/
244250
int next();

0 commit comments

Comments
 (0)