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
70 @SuppressWarnings("unchecked")
71 public synchronized AtomicStampedValue<V> copy() {
72 return (AtomicStampedValue<V>) this.clone();
76 * Synchronized implementation of clone with exception swallowing
79 protected synchronized Object clone() {
82 } catch (CloneNotSupportedException e) {
83 // We should never end up here since this class implements Cloneable
84 throw new RuntimeException(e);
89 * Copy data atomically if data is after certain stamp ("fresh" enough)
92 * @return null, if the stamp of this instance is before stampMin. Otherwise return the data copied
94 public synchronized @Nullable AtomicStampedValue<V> copyIfStampAfter(long stampMin) {
95 if (stampMin <= this.stamp) {
96 return new AtomicStampedValue<>(this);
105 public long getStamp() {
112 public V getValue() {
117 * Compare two AtomicStampedKeyValue objects based on stamps
119 * Nulls are ordered first
121 * @param x first instance
122 * @param y second instance
123 * @return a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater
126 public static int compare(@SuppressWarnings("rawtypes") @Nullable AtomicStampedValue x,
127 @SuppressWarnings("rawtypes") @Nullable AtomicStampedValue y) {
130 } else if (y == null) {
133 return Long.compare(x.stamp, y.stamp);