]> git.basschouten.com Git - openhab-addons.git/blob
69cdfceb691b4d5798e8b3d105a3060c695e45b7
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2023 Contributors to the openHAB project
3  *
4  * See the NOTICE file(s) distributed with this work for additional
5  * information.
6  *
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
10  *
11  * SPDX-License-Identifier: EPL-2.0
12  */
13 package org.openhab.binding.homeconnect.internal.client;
14
15 import java.util.ArrayList;
16 import java.util.Collection;
17 import java.util.concurrent.ArrayBlockingQueue;
18
19 import org.eclipse.jdt.annotation.NonNullByDefault;
20
21 /**
22  * FIFO queue (ring buffer implementation).
23  *
24  * @author Jonas BrĂ¼stel - Initial contribution
25  *
26  */
27 @NonNullByDefault
28 public class CircularQueue<E> {
29
30     private final ArrayBlockingQueue<E> queue;
31
32     public CircularQueue(final int capacity) {
33         queue = new ArrayBlockingQueue<>(capacity);
34     }
35
36     public synchronized void add(E element) {
37         ArrayBlockingQueue<E> myQueue = queue;
38         if (myQueue.remainingCapacity() <= 0) {
39             myQueue.poll();
40         }
41         myQueue.add(element);
42     }
43
44     public synchronized void addAll(Collection<? extends E> collection) {
45         collection.forEach(this::add);
46     }
47
48     public synchronized Collection<E> getAll() {
49         return new ArrayList<>(queue);
50     }
51 }