2 * Copyright (c) 2010-2020 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
7 * This program and the accompanying materials are made available under the
8 * terms of the Eclipse Public License 2.0 which is available at
9 * http://www.eclipse.org/legal/epl-2.0
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.io.transport.modbus.internal;
15 import org.apache.commons.pool2.impl.DefaultEvictionPolicy;
16 import org.apache.commons.pool2.impl.EvictionPolicy;
17 import org.apache.commons.pool2.impl.GenericKeyedObjectPoolConfig;
18 import org.eclipse.jdt.annotation.NonNullByDefault;
19 import org.eclipse.jdt.annotation.Nullable;
20 import org.openhab.io.transport.modbus.internal.pooling.ModbusSlaveConnectionEvictionPolicy;
22 import net.wimpi.modbus.net.ModbusSlaveConnection;
25 * Configuration for Modbus connection pool
28 * - there is only one connection per endpoint
29 * - clients are served "fairly" (first-come-first-serve)
31 * @author Sami Salonen - Initial contribution
35 public class ModbusPoolConfig extends GenericKeyedObjectPoolConfig<ModbusSlaveConnection> {
37 @SuppressWarnings("unused")
38 private EvictionPolicy<ModbusSlaveConnection> evictionPolicy = new DefaultEvictionPolicy<>();
40 public ModbusPoolConfig() {
41 // When the pool is exhausted, multiple calling threads may be simultaneously blocked waiting for instances
43 // become available. As of pool 1.5, a "fairness" algorithm has been implemented to ensure that threads
45 // available instances in request arrival order.
48 // Limit one connection per endpoint (i.e. same ip:port pair or same serial device).
49 // If there are multiple read/write requests to process at the same time, block until previous one finishes
50 setBlockWhenExhausted(true);
53 // block infinitely when exhausted
56 // Connections are "tested" on return. Effectively, disconnected connections are destroyed when returning on
58 // Note that we do not test on borrow -- that would mean blocking situation when connection cannot be
60 // Instead, borrowing connection from pool can return unconnected connection.
61 setTestOnReturn(true);
66 // Evict idle connections every 10 seconds
67 setEvictionPolicy(new ModbusSlaveConnectionEvictionPolicy());
68 setTimeBetweenEvictionRunsMillis(10000);
69 // Let eviction re-create ready-to-use idle (=unconnected) connections
70 // This is to avoid occasional / rare deadlocks seen with pool 2.8.1 & 2.4.3 when
71 // borrow hangs (waiting indefinitely for idle object to appear in the pool)
72 // https://github.com/openhab/openhab-addons/issues/8460
77 public void setEvictionPolicyClassName(@Nullable String evictionPolicyClassName) {
78 // Protect against https://issues.apache.org/jira/browse/POOL-338
79 // Disallow re-setting eviction policy with class name. Only setEvictionPolicy allowed
80 throw new IllegalStateException("setEvictionPolicyClassName disallowed! Will fail in OSGI");