io.axoniq.flowcontrol.producer.grpc.subscriptions.RoundRobinSubscriptions Maven / Gradle / Ivy
/*
* Copyright (c) 2021. AxonIQ
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.axoniq.flowcontrol.producer.grpc.subscriptions;
import io.axoniq.flowcontrol.producer.grpc.ActiveSubscriptions;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
* @author Sara Pellegrini
* @author Milan Savic
* @since 1.0
*/
public class RoundRobinSubscriptions implements ActiveSubscriptions {
private final List subscriptions = new CopyOnWriteArrayList<>();
private final AtomicInteger index = new AtomicInteger(0);
private final ReentrantReadWriteLock.ReadLock readLock;
private final ReentrantReadWriteLock.WriteLock writeLock;
public RoundRobinSubscriptions() {
ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();
readLock = readWriteLock.readLock();
writeLock = readWriteLock.writeLock();
}
@Override
public void add(ActiveSubscription subscription) {
writeLock.lock();
try {
subscriptions.add(subscription);
} finally {
writeLock.unlock();
}
}
@Override
public void remove(ActiveSubscription subscription) {
writeLock.lock();
try {
subscriptions.remove(subscription);
} finally {
writeLock.unlock();
}
}
@Override
public boolean hasNext() {
readLock.lock();
try {
return !subscriptions.isEmpty();
} finally {
readLock.unlock();
}
}
@Override
public Optional next() {
readLock.lock();
try {
if (subscriptions.isEmpty()) {
return Optional.empty();
}
if (index.get() >= subscriptions.size() - 1) {
index.set(0);
} else {
index.incrementAndGet();
}
return Optional.of(subscriptions.get(index.get()));
} finally {
readLock.unlock();
}
}
}