/*
 * The Alluxio Open Foundation licenses this work under the Apache License, version 2.0
 * (the “License”). You may not use this work except in compliance with the License, which is
 * available at www.apache.org/licenses/LICENSE-2.0
 *
 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied, as more fully set forth in the License.
 *
 * See the NOTICE file distributed with this work for information regarding copyright ownership.
 */

package alluxio.master.journal;

import alluxio.Constants;
import alluxio.master.MasterContext;
import alluxio.proto.journal.Journal.JournalEntry;

import com.google.common.base.Preconditions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.ReentrantLock;

/**
 * This enables async journal writing, as well as some batched journal flushing.
 */
public final class AsyncJournalWriter {
  private static final Logger LOG = LoggerFactory.getLogger(Constants.LOGGER_TYPE);

  private final JournalWriter mJournalWriter;
  private final ConcurrentLinkedQueue<JournalEntry> mQueue;
  private final AtomicLong mCounter;
  private final AtomicLong mFlushCounter;
  private final long mFlushBatchTime;

  /**
   * Use a {@link ReentrantLock} to guard the journal writing. Using the fairness policy seems to
   * result in better throughput.
   */
  private final ReentrantLock mFlushLock = new ReentrantLock(true);

  /**
   * Creates a {@link AsyncJournalWriter}.
   *
   * @param journalWriter the {@link JournalWriter} to use for writing
   */
  public AsyncJournalWriter(JournalWriter journalWriter) {
    mJournalWriter = Preconditions.checkNotNull(journalWriter);
    mQueue = new ConcurrentLinkedQueue<>();
    mCounter = new AtomicLong(0);
    mFlushCounter = new AtomicLong(0);
    mFlushBatchTime = MasterContext.getConf().getLong(Constants.MASTER_JOURNAL_FLUSH_BATCH_TIME_MS);
  }

  /**
   * Appends a {@link JournalEntry} for writing to the journal.
   *
   * @param entry the {@link JournalEntry} to append
   * @return a counter for the entry, for flushing
   */
  public long appendEntry(JournalEntry entry) {
    mCounter.incrementAndGet();
    mQueue.offer(entry);
    return mCounter.get();
  }

  /**
   * Flushes and waits until the specified counter is flushed to the journal. If the specified
   * counter is already flushed, this is essentially a no-op.
   *
   * @param counter the counter to flush
   * @throws IOException if an error occurs in flushing the journal
   */
  public void flush(final long counter) throws IOException {
    if (counter <= mFlushCounter.get()) {
      return;
    }
    // Using reentrant lock, since it seems to result in higher throughput than using 'synchronized'
    mFlushLock.lock();
    try {
      long startTime = System.currentTimeMillis();
      long flushCounter = mFlushCounter.get();
      if (counter <= flushCounter) {
        return;
      }
      while (counter > flushCounter) {
        for (;;) {
          JournalEntry entry = mQueue.poll();
          if (entry == null) {
            // No more entries in the queue.
            break;
          }
          mJournalWriter.getEntryOutputStream().writeEntry(entry);
          flushCounter++;

          if (flushCounter >= counter) {
            if ((System.currentTimeMillis() - startTime) >= mFlushBatchTime) {
              // This thread has been writing to the journal for enough time.
              break;
            }
          }
        }
      }
      mJournalWriter.getEntryOutputStream().flush();
      mFlushCounter.set(flushCounter);
    } finally {
      mFlushLock.unlock();
    }
  }

}

@@ -934,16 +934,64 @@
 tLock;%0A%0A
+import javax.annotation.concurrent.ThreadSafe;%0A%0A
 /**%0A * T
@@ -1071,16 +1071,28 @@
 ng.%0A */%0A
+@ThreadSafe%0A
 public f
@@ -1208,16 +1208,17 @@
 TYPE);%0A%0A
+%0A
   privat
@@ -2352,24 +2352,1063 @@
 ry entry) %7B%0A
+    // TODO(gpang): handle bounding the queue if it becomes too large.%0A%0A    /**%0A     * Protocol for appending entries%0A     *%0A     * This protocol is lock free, to reduce the overhead in critical sections. It uses%0A     * %7B@link AtomicLong%7D and %7B@link ConcurrentLinkedQueue%7D which are both lock-free.%0A     *%0A     * The invariant that must be satisfied is that the 'counter' that is returned must be%0A     * greater than or equal to the actual counter of the entry in the queue.%0A     *%0A     * In order to guarantee the invariant, the %7B@link #mCounter%7D is incremented before adding the%0A     * entry to the %7B@link #mQueue%7D. AFTER the counter is incremented, whenever the counter is%0A     * read, it is guaranteed to be greater than or equal to the counter for the queue entries.%0A     *%0A     * Therefore, the %7B@link #mCounter%7D must be read AFTER the entry is added to the queue. The%0A     * resulting read of the counter AFTER the entry is added is guaranteed to be greater than or%0A     * equal to the counter for the entries in the queue.%0A     */%0A
     mCounter
@@ -4151,32 +4151,101 @@
 flushCounter) %7B%0A
+        // The specified counter is already flushed, so just return.%0A
         return;%0A
@@ -4427,24 +4427,60 @@
 n the queue.
+ Break out of the infinite for-loop.
 %0A           
@@ -4709,24 +4709,24 @@
 atchTime) %7B%0A
-
             
@@ -4790,16 +4790,69 @@
 gh time.
+ Break out of the%0A              // infinite for-loop.
 %0A       

Add explanation comments for AsyncJournalWriter