2 * Copyright (c) 2010-2023 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.binding.modbus.internal;
15 import java.util.Objects;
17 import org.eclipse.jdt.annotation.NonNullByDefault;
18 import org.eclipse.jdt.annotation.Nullable;
21 * Timestamp-value pair that can be updated atomically
23 * @author Sami Salonen - Initial contribution
25 * @param <V> type of the value
28 public class AtomicStampedValue<V> implements Cloneable {
33 private AtomicStampedValue(AtomicStampedValue<V> copy) {
34 this(copy.stamp, copy.value);
38 * Construct new stamped key-value pair
40 * @param stamp stamp for the data
41 * @param value value for the data
43 * @throws NullPointerException when key or value is null
45 public AtomicStampedValue(long stamp, V value) {
46 Objects.requireNonNull(value, "value should not be null!");
52 * Update data in this instance atomically
54 * @param stamp stamp for the data
55 * @param value value for the data
57 * @throws NullPointerException when value is null
59 public synchronized void update(long stamp, V value) {
60 Objects.requireNonNull(value, "value should not be null!");
66 * Copy data atomically and return the new (shallow) copy
68 * @return new copy of the data
69 * @throws CloneNotSupportedException
71 @SuppressWarnings("unchecked")
72 public synchronized AtomicStampedValue<V> copy() {
73 return (AtomicStampedValue<V>) this.clone();
77 * Synchronized implementation of clone with exception swallowing
80 protected synchronized Object clone() {
83 } catch (CloneNotSupportedException e) {
84 // We should never end up here since this class implements Cloneable
85 throw new RuntimeException(e);
90 * Copy data atomically if data is after certain stamp ("fresh" enough)
93 * @return null, if the stamp of this instance is before stampMin. Otherwise return the data copied
95 public synchronized @Nullable AtomicStampedValue<V> copyIfStampAfter(long stampMin) {
96 if (stampMin <= this.stamp) {
97 return new AtomicStampedValue<>(this);
106 public long getStamp() {
113 public V getValue() {
118 * Compare two AtomicStampedKeyValue objects based on stamps
120 * Nulls are ordered first
122 * @param x first instance
123 * @param y second instance
124 * @return a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater
127 public static int compare(@SuppressWarnings("rawtypes") @Nullable AtomicStampedValue x,
128 @SuppressWarnings("rawtypes") @Nullable AtomicStampedValue y) {
131 } else if (y == null) {
134 return Long.compare(x.stamp, y.stamp);