001/*
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *     http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018package org.apache.hadoop.hbase.regionserver.wal;
019
020import static org.apache.hadoop.hbase.util.FutureUtils.addListener;
021
022import java.util.concurrent.CompletableFuture;
023import java.util.concurrent.atomic.AtomicInteger;
024import org.apache.hadoop.hbase.wal.WAL.Entry;
025import org.apache.hadoop.hbase.wal.WALProvider.AsyncWriter;
026import org.apache.yetus.audience.InterfaceAudience;
027
028import org.apache.hbase.thirdparty.com.google.common.collect.ImmutableList;
029
030/**
031 * An {@link AsyncWriter} wrapper which writes data to a set of {@link AsyncWriter} instances.
032 */
033@InterfaceAudience.Private
034public final class CombinedAsyncWriter extends CombinedWriterBase<AsyncWriter>
035  implements AsyncWriter {
036
037  private CombinedAsyncWriter(ImmutableList<AsyncWriter> writers) {
038    super(writers);
039  }
040
041  @Override
042  public void append(Entry entry) {
043    writers.forEach(w -> w.append(entry));
044  }
045
046  @Override
047  public CompletableFuture<Long> sync(boolean forceSync) {
048    CompletableFuture<Long> future = new CompletableFuture<>();
049    AtomicInteger remaining = new AtomicInteger(writers.size());
050    writers.forEach(w -> addListener(w.sync(forceSync), (length, error) -> {
051      if (error != null) {
052        future.completeExceptionally(error);
053        return;
054      }
055      if (remaining.decrementAndGet() == 0) {
056        future.complete(length);
057      }
058    }));
059    return future;
060  }
061
062  public static CombinedAsyncWriter create(AsyncWriter writer, AsyncWriter... writers) {
063    return new CombinedAsyncWriter(
064      ImmutableList.<AsyncWriter> builder().add(writer).add(writers).build());
065  }
066}