2 * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package org.opendaylight.controller.cluster.databroker.actors.dds;
10 import com.google.common.base.Preconditions;
11 import com.google.common.base.Verify;
12 import com.google.common.util.concurrent.AbstractFuture;
13 import java.util.ArrayList;
14 import java.util.Collection;
15 import java.util.Iterator;
16 import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
17 import javax.annotation.concurrent.GuardedBy;
20 * An {@link AbstractFuture} implementation which requires a certain number of votes before it completes. If all votes
21 * are 'yes', then it completes with a pre-determined value. If any of the votes are 'no', the future completes with
22 * an exception. This exception corresponds to the cause reported by the first 'no' vote, with all subsequent votes
23 * added as suppressed exceptions.
25 * Implementation is geared toward positive votes. Negative votes have to synchronize and therefore are more likely
28 * @author Robert Varga
30 * @param <T> Type of value returned on success
32 class VotingFuture<T> extends AbstractFuture<T> {
33 @SuppressWarnings("rawtypes")
34 private static final AtomicIntegerFieldUpdater<VotingFuture> VOTES_UPDATER =
35 AtomicIntegerFieldUpdater.newUpdater(VotingFuture.class, "neededVotes");
37 private final T result;
39 @GuardedBy("failures")
40 private final Collection<Throwable> failures = new ArrayList<>(0);
41 @SuppressWarnings("unused")
42 private volatile int neededVotes;
44 VotingFuture(final T result, final int requiredVotes) {
45 Preconditions.checkArgument(requiredVotes > 0);
46 this.neededVotes = requiredVotes;
48 // null is okay to allow Void type
54 synchronized (failures) {
60 void voteNo(final Throwable cause) {
61 synchronized (failures) {
69 private boolean castVote() {
70 final int votes = VOTES_UPDATER.decrementAndGet(this);
71 Verify.verify(votes >= 0);
75 @GuardedBy("failures")
76 private void resolveResult() {
77 final Iterator<Throwable> it = failures.iterator();
83 final Throwable t = it.next();
84 while (it.hasNext()) {
85 t.addSuppressed(it.next());