View Javadoc

1   /**
2    *
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *     http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing, software
14   * distributed under the License is distributed on an "AS IS" BASIS,
15   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16   * See the License for the specific language governing permissions and
17   * limitations under the License.
18   */
19  package org.apache.hadoop.hbase.regionserver;
20  
21  import static org.apache.hadoop.util.StringUtils.humanReadableInt;
22  
23  import java.io.IOException;
24  import java.lang.Thread.UncaughtExceptionHandler;
25  import java.lang.management.MemoryUsage;
26  import java.util.ArrayList;
27  import java.util.ConcurrentModificationException;
28  import java.util.HashMap;
29  import java.util.HashSet;
30  import java.util.List;
31  import java.util.Map;
32  import java.util.Objects;
33  import java.util.Set;
34  import java.util.SortedMap;
35  import java.util.concurrent.BlockingQueue;
36  import java.util.concurrent.DelayQueue;
37  import java.util.concurrent.Delayed;
38  import java.util.concurrent.ThreadFactory;
39  import java.util.concurrent.TimeUnit;
40  import java.util.concurrent.atomic.AtomicBoolean;
41  import java.util.concurrent.locks.ReentrantReadWriteLock;
42  
43  import org.apache.commons.logging.Log;
44  import org.apache.commons.logging.LogFactory;
45  import org.apache.hadoop.conf.Configuration;
46  import org.apache.hadoop.hbase.DroppedSnapshotException;
47  import org.apache.hadoop.hbase.HConstants;
48  import org.apache.hadoop.hbase.RemoteExceptionHandler;
49  import org.apache.hadoop.hbase.classification.InterfaceAudience;
50  import org.apache.hadoop.hbase.client.RegionReplicaUtil;
51  import org.apache.hadoop.hbase.io.util.HeapMemorySizeUtil;
52  import org.apache.hadoop.hbase.regionserver.Region.FlushResult;
53  import org.apache.hadoop.hbase.util.Bytes;
54  import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
55  import org.apache.hadoop.hbase.util.HasThread;
56  import org.apache.hadoop.hbase.util.ServerRegionReplicaUtil;
57  import org.apache.hadoop.hbase.util.Threads;
58  import org.apache.hadoop.util.StringUtils;
59  import org.apache.hadoop.util.StringUtils.TraditionalBinaryPrefix;
60  import org.apache.htrace.Trace;
61  import org.apache.htrace.TraceScope;
62  import org.apache.hadoop.hbase.util.Counter;
63  
64  import com.google.common.base.Preconditions;
65  
66  /**
67   * Thread that flushes cache on request
68   *
69   * NOTE: This class extends Thread rather than Chore because the sleep time
70   * can be interrupted when there is something to do, rather than the Chore
71   * sleep time which is invariant.
72   *
73   * @see FlushRequester
74   */
75  @InterfaceAudience.Private
76  class MemStoreFlusher implements FlushRequester {
77    private static final Log LOG = LogFactory.getLog(MemStoreFlusher.class);
78  
79    private Configuration conf;
80    // These two data members go together.  Any entry in the one must have
81    // a corresponding entry in the other.
82    private final BlockingQueue<FlushQueueEntry> flushQueue =
83      new DelayQueue<FlushQueueEntry>();
84    private final Map<Region, FlushRegionEntry> regionsInQueue =
85      new HashMap<Region, FlushRegionEntry>();
86    private AtomicBoolean wakeupPending = new AtomicBoolean();
87  
88    private final long threadWakeFrequency;
89    private final HRegionServer server;
90    private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
91    private final Object blockSignal = new Object();
92  
93    protected long globalMemStoreLimit;
94    protected float globalMemStoreLimitLowMarkPercent;
95    protected long globalMemStoreLimitLowMark;
96  
97    private long blockingWaitTime;
98    private final Counter updatesBlockedMsHighWater = new Counter();
99  
100   private final FlushHandler[] flushHandlers;
101   private List<FlushRequestListener> flushRequestListeners = new ArrayList<FlushRequestListener>(1);
102 
103   /**
104    * @param conf
105    * @param server
106    */
107   public MemStoreFlusher(final Configuration conf,
108       final HRegionServer server) {
109     super();
110     this.conf = conf;
111     this.server = server;
112     this.threadWakeFrequency =
113       conf.getLong(HConstants.THREAD_WAKE_FREQUENCY, 10 * 1000);
114     long max = -1L;
115     final MemoryUsage usage = HeapMemorySizeUtil.safeGetHeapMemoryUsage();
116     if (usage != null) {
117       max = usage.getMax();
118     }
119     float globalMemStorePercent = HeapMemorySizeUtil.getGlobalMemStorePercent(conf, true);
120     this.globalMemStoreLimit = (long) (max * globalMemStorePercent);
121     this.globalMemStoreLimitLowMarkPercent =
122         HeapMemorySizeUtil.getGlobalMemStoreLowerMark(conf, globalMemStorePercent);
123     this.globalMemStoreLimitLowMark =
124         (long) (this.globalMemStoreLimit * this.globalMemStoreLimitLowMarkPercent);
125 
126     this.blockingWaitTime = conf.getInt("hbase.hstore.blockingWaitTime",
127       90000);
128     int handlerCount = conf.getInt("hbase.hstore.flusher.count", 2);
129     this.flushHandlers = new FlushHandler[handlerCount];
130     LOG.info("globalMemStoreLimit="
131         + TraditionalBinaryPrefix.long2String(this.globalMemStoreLimit, "", 1)
132         + ", globalMemStoreLimitLowMark="
133         + TraditionalBinaryPrefix.long2String(this.globalMemStoreLimitLowMark, "", 1)
134         + ", maxHeap=" + TraditionalBinaryPrefix.long2String(max, "", 1));
135   }
136 
137   public Counter getUpdatesBlockedMsHighWater() {
138     return this.updatesBlockedMsHighWater;
139   }
140 
141   /**
142    * The memstore across all regions has exceeded the low water mark. Pick
143    * one region to flush and flush it synchronously (this is called from the
144    * flush thread)
145    * @return true if successful
146    */
147   private boolean flushOneForGlobalPressure() {
148     SortedMap<Long, Region> regionsBySize = server.getCopyOfOnlineRegionsSortedBySize();
149     Set<Region> excludedRegions = new HashSet<Region>();
150 
151     double secondaryMultiplier
152       = ServerRegionReplicaUtil.getRegionReplicaStoreFileRefreshMultiplier(conf);
153 
154     boolean flushedOne = false;
155     while (!flushedOne) {
156       // Find the biggest region that doesn't have too many storefiles
157       // (might be null!)
158       Region bestFlushableRegion = getBiggestMemstoreRegion(regionsBySize, excludedRegions, true);
159       // Find the biggest region, total, even if it might have too many flushes.
160       Region bestAnyRegion = getBiggestMemstoreRegion(
161           regionsBySize, excludedRegions, false);
162       // Find the biggest region that is a secondary region
163       Region bestRegionReplica = getBiggestMemstoreOfRegionReplica(regionsBySize,
164         excludedRegions);
165 
166       if (bestAnyRegion == null && bestRegionReplica == null) {
167         LOG.error("Above memory mark but there are no flushable regions!");
168         return false;
169       }
170 
171       Region regionToFlush;
172       if (bestFlushableRegion != null &&
173           bestAnyRegion.getMemstoreSize() > 2 * bestFlushableRegion.getMemstoreSize()) {
174         // Even if it's not supposed to be flushed, pick a region if it's more than twice
175         // as big as the best flushable one - otherwise when we're under pressure we make
176         // lots of little flushes and cause lots of compactions, etc, which just makes
177         // life worse!
178         if (LOG.isDebugEnabled()) {
179           LOG.debug("Under global heap pressure: " + "Region "
180               + bestAnyRegion.getRegionInfo().getRegionNameAsString()
181               + " has too many " + "store files, but is "
182               + TraditionalBinaryPrefix.long2String(bestAnyRegion.getMemstoreSize(), "", 1)
183               + " vs best flushable region's "
184               + TraditionalBinaryPrefix.long2String(bestFlushableRegion.getMemstoreSize(), "", 1)
185               + ". Choosing the bigger.");
186         }
187         regionToFlush = bestAnyRegion;
188       } else {
189         if (bestFlushableRegion == null) {
190           regionToFlush = bestAnyRegion;
191         } else {
192           regionToFlush = bestFlushableRegion;
193         }
194       }
195 
196       Preconditions.checkState(
197         (regionToFlush != null && regionToFlush.getMemstoreSize() > 0) ||
198         (bestRegionReplica != null && bestRegionReplica.getMemstoreSize() > 0));
199 
200       if (regionToFlush == null ||
201           (bestRegionReplica != null &&
202            ServerRegionReplicaUtil.isRegionReplicaStoreFileRefreshEnabled(conf) &&
203            (bestRegionReplica.getMemstoreSize()
204                > secondaryMultiplier * regionToFlush.getMemstoreSize()))) {
205         LOG.info("Refreshing storefiles of region " + bestRegionReplica +
206           " due to global heap pressure. memstore size=" + StringUtils.humanReadableInt(
207             server.getRegionServerAccounting().getGlobalMemstoreSize()));
208         flushedOne = refreshStoreFilesAndReclaimMemory(bestRegionReplica);
209         if (!flushedOne) {
210           LOG.info("Excluding secondary region " + bestRegionReplica +
211               " - trying to find a different region to refresh files.");
212           excludedRegions.add(bestRegionReplica);
213         }
214       } else {
215         LOG.info("Flush of region " + regionToFlush + " due to global heap pressure. "
216             + "Total Memstore size="
217             + humanReadableInt(server.getRegionServerAccounting().getGlobalMemstoreSize())
218             + ", Region memstore size="
219             + humanReadableInt(regionToFlush.getMemstoreSize()));
220         flushedOne = flushRegion(regionToFlush, true, false);
221 
222         if (!flushedOne) {
223           LOG.info("Excluding unflushable region " + regionToFlush +
224               " - trying to find a different region to flush.");
225           excludedRegions.add(regionToFlush);
226         }
227       }
228     }
229     return true;
230   }
231 
232   private class FlushHandler extends HasThread {
233 
234     private FlushHandler(String name) {
235       super(name);
236     }
237 
238     @Override
239     public void run() {
240       while (!server.isStopped()) {
241         FlushQueueEntry fqe = null;
242         try {
243           wakeupPending.set(false); // allow someone to wake us up again
244           fqe = flushQueue.poll(threadWakeFrequency, TimeUnit.MILLISECONDS);
245           if (fqe == null || fqe instanceof WakeupFlushThread) {
246             if (isAboveLowWaterMark()) {
247               LOG.debug("Flush thread woke up because memory above low water="
248                   + TraditionalBinaryPrefix.long2String(globalMemStoreLimitLowMark, "", 1));
249               if (!flushOneForGlobalPressure()) {
250                 // Wasn't able to flush any region, but we're above low water mark
251                 // This is unlikely to happen, but might happen when closing the
252                 // entire server - another thread is flushing regions. We'll just
253                 // sleep a little bit to avoid spinning, and then pretend that
254                 // we flushed one, so anyone blocked will check again
255                 Thread.sleep(1000);
256                 wakeUpIfBlocking();
257               }
258               // Enqueue another one of these tokens so we'll wake up again
259               wakeupFlushThread();
260             }
261             continue;
262           }
263           FlushRegionEntry fre = (FlushRegionEntry) fqe;
264           if (!flushRegion(fre)) {
265             break;
266           }
267         } catch (InterruptedException ex) {
268           continue;
269         } catch (ConcurrentModificationException ex) {
270           continue;
271         } catch (Exception ex) {
272           LOG.error("Cache flusher failed for entry " + fqe, ex);
273           if (!server.checkFileSystem()) {
274             break;
275           }
276         }
277       }
278       synchronized (regionsInQueue) {
279         regionsInQueue.clear();
280         flushQueue.clear();
281       }
282 
283       // Signal anyone waiting, so they see the close flag
284       wakeUpIfBlocking();
285       LOG.info(getName() + " exiting");
286     }
287   }
288 
289 
290   private void wakeupFlushThread() {
291     if (wakeupPending.compareAndSet(false, true)) {
292       flushQueue.add(new WakeupFlushThread());
293     }
294   }
295 
296   private Region getBiggestMemstoreRegion(
297       SortedMap<Long, Region> regionsBySize,
298       Set<Region> excludedRegions,
299       boolean checkStoreFileCount) {
300     synchronized (regionsInQueue) {
301       for (Region region : regionsBySize.values()) {
302         if (excludedRegions.contains(region)) {
303           continue;
304         }
305 
306         if (((HRegion)region).writestate.flushing ||
307             !((HRegion)region).writestate.writesEnabled) {
308           continue;
309         }
310 
311         if (checkStoreFileCount && isTooManyStoreFiles(region)) {
312           continue;
313         }
314         return region;
315       }
316     }
317     return null;
318   }
319 
320   private Region getBiggestMemstoreOfRegionReplica(SortedMap<Long, Region> regionsBySize,
321       Set<Region> excludedRegions) {
322     synchronized (regionsInQueue) {
323       for (Region region : regionsBySize.values()) {
324         if (excludedRegions.contains(region)) {
325           continue;
326         }
327 
328         if (RegionReplicaUtil.isDefaultReplica(region.getRegionInfo())) {
329           continue;
330         }
331 
332         return region;
333       }
334     }
335     return null;
336   }
337 
338   private boolean refreshStoreFilesAndReclaimMemory(Region region) {
339     try {
340       return region.refreshStoreFiles();
341     } catch (IOException e) {
342       LOG.warn("Refreshing store files failed with exception", e);
343     }
344     return false;
345   }
346 
347   /**
348    * Return true if global memory usage is above the high watermark
349    */
350   private boolean isAboveHighWaterMark() {
351     return server.getRegionServerAccounting().
352       getGlobalMemstoreSize() >= globalMemStoreLimit;
353   }
354 
355   /**
356    * Return true if we're above the high watermark
357    */
358   private boolean isAboveLowWaterMark() {
359     return server.getRegionServerAccounting().
360       getGlobalMemstoreSize() >= globalMemStoreLimitLowMark;
361   }
362 
363   @Override
364   public void requestFlush(Region r, boolean forceFlushAllStores) {
365     ((HRegion)r).incrementFlushesQueuedCount();
366     synchronized (regionsInQueue) {
367       if (!regionsInQueue.containsKey(r)) {
368         // This entry has no delay so it will be added at the top of the flush
369         // queue.  It'll come out near immediately.
370         FlushRegionEntry fqe = new FlushRegionEntry(r, forceFlushAllStores);
371         this.regionsInQueue.put(r, fqe);
372         this.flushQueue.add(fqe);
373       }
374     }
375   }
376 
377   @Override
378   public void requestDelayedFlush(Region r, long delay, boolean forceFlushAllStores) {
379     ((HRegion)r).incrementFlushesQueuedCount();
380     synchronized (regionsInQueue) {
381       if (!regionsInQueue.containsKey(r)) {
382         // This entry has some delay
383         FlushRegionEntry fqe = new FlushRegionEntry(r, forceFlushAllStores);
384         fqe.requeue(delay);
385         this.regionsInQueue.put(r, fqe);
386         this.flushQueue.add(fqe);
387       }
388     }
389   }
390 
391   public int getFlushQueueSize() {
392     return flushQueue.size();
393   }
394 
395   /**
396    * Only interrupt once it's done with a run through the work loop.
397    */
398   void interruptIfNecessary() {
399     lock.writeLock().lock();
400     try {
401       for (FlushHandler flushHander : flushHandlers) {
402         if (flushHander != null) flushHander.interrupt();
403       }
404     } finally {
405       lock.writeLock().unlock();
406     }
407   }
408 
409   synchronized void start(UncaughtExceptionHandler eh) {
410     ThreadFactory flusherThreadFactory = Threads.newDaemonThreadFactory(
411         server.getServerName().toShortString() + "-MemStoreFlusher", eh);
412     for (int i = 0; i < flushHandlers.length; i++) {
413       flushHandlers[i] = new FlushHandler("MemStoreFlusher." + i);
414       flusherThreadFactory.newThread(flushHandlers[i]);
415       flushHandlers[i].start();
416     }
417   }
418 
419   boolean isAlive() {
420     for (FlushHandler flushHander : flushHandlers) {
421       if (flushHander != null && flushHander.isAlive()) {
422         return true;
423       }
424     }
425     return false;
426   }
427 
428   void join() {
429     for (FlushHandler flushHander : flushHandlers) {
430       if (flushHander != null) {
431         Threads.shutdown(flushHander.getThread());
432       }
433     }
434   }
435 
436   /**
437    * A flushRegion that checks store file count.  If too many, puts the flush
438    * on delay queue to retry later.
439    * @param fqe
440    * @return true if the region was successfully flushed, false otherwise. If
441    * false, there will be accompanying log messages explaining why the region was
442    * not flushed.
443    */
444   private boolean flushRegion(final FlushRegionEntry fqe) {
445     Region region = fqe.region;
446     if (!region.getRegionInfo().isMetaRegion() &&
447         isTooManyStoreFiles(region)) {
448       if (fqe.isMaximumWait(this.blockingWaitTime)) {
449         LOG.info("Waited " + (EnvironmentEdgeManager.currentTime() - fqe.createTime) +
450           "ms on a compaction to clean up 'too many store files'; waited " +
451           "long enough... proceeding with flush of " +
452           region.getRegionInfo().getRegionNameAsString());
453       } else {
454         // If this is first time we've been put off, then emit a log message.
455         if (fqe.getRequeueCount() <= 0) {
456           // Note: We don't impose blockingStoreFiles constraint on meta regions
457           LOG.warn("Region " + region.getRegionInfo().getRegionNameAsString() + " has too many " +
458             "store files; delaying flush up to " + this.blockingWaitTime + "ms");
459           if (!this.server.compactSplitThread.requestSplit(region)) {
460             try {
461               this.server.compactSplitThread.requestSystemCompaction(
462                   region, Thread.currentThread().getName());
463             } catch (IOException e) {
464               LOG.error("Cache flush failed for region " +
465                   Bytes.toStringBinary(region.getRegionInfo().getRegionName()),
466                 RemoteExceptionHandler.checkIOException(e));
467             }
468           }
469         }
470 
471         // Put back on the queue.  Have it come back out of the queue
472         // after a delay of this.blockingWaitTime / 100 ms.
473         this.flushQueue.add(fqe.requeue(this.blockingWaitTime / 100));
474         // Tell a lie, it's not flushed but it's ok
475         return true;
476       }
477     }
478     return flushRegion(region, false, fqe.isForceFlushAllStores());
479   }
480 
481   /**
482    * Flush a region.
483    * @param region Region to flush.
484    * @param emergencyFlush Set if we are being force flushed. If true the region
485    * needs to be removed from the flush queue. If false, when we were called
486    * from the main flusher run loop and we got the entry to flush by calling
487    * poll on the flush queue (which removed it).
488    * @param forceFlushAllStores whether we want to flush all store.
489    * @return true if the region was successfully flushed, false otherwise. If
490    * false, there will be accompanying log messages explaining why the region was
491    * not flushed.
492    */
493   private boolean flushRegion(final Region region, final boolean emergencyFlush,
494       boolean forceFlushAllStores) {
495     synchronized (this.regionsInQueue) {
496       FlushRegionEntry fqe = this.regionsInQueue.remove(region);
497       // Use the start time of the FlushRegionEntry if available
498       if (fqe != null && emergencyFlush) {
499         // Need to remove from region from delay queue.  When NOT an
500         // emergencyFlush, then item was removed via a flushQueue.poll.
501         flushQueue.remove(fqe);
502       }
503     }
504 
505     lock.readLock().lock();
506     try {
507       notifyFlushRequest(region, emergencyFlush);
508       FlushResult flushResult = region.flush(forceFlushAllStores);
509       boolean shouldCompact = flushResult.isCompactionNeeded();
510       // We just want to check the size
511       boolean shouldSplit = ((HRegion)region).checkSplit() != null;
512       if (shouldSplit) {
513         this.server.compactSplitThread.requestSplit(region);
514       } else if (shouldCompact) {
515         server.compactSplitThread.requestSystemCompaction(
516             region, Thread.currentThread().getName());
517       }
518     } catch (DroppedSnapshotException ex) {
519       // Cache flush can fail in a few places. If it fails in a critical
520       // section, we get a DroppedSnapshotException and a replay of wal
521       // is required. Currently the only way to do this is a restart of
522       // the server. Abort because hdfs is probably bad (HBASE-644 is a case
523       // where hdfs was bad but passed the hdfs check).
524       server.abort("Replay of WAL required. Forcing server shutdown", ex);
525       return false;
526     } catch (IOException ex) {
527       LOG.error("Cache flush failed" + (region != null ? (" for region " +
528           Bytes.toStringBinary(region.getRegionInfo().getRegionName())) : ""),
529         RemoteExceptionHandler.checkIOException(ex));
530       if (!server.checkFileSystem()) {
531         return false;
532       }
533     } finally {
534       lock.readLock().unlock();
535       wakeUpIfBlocking();
536     }
537     return true;
538   }
539 
540   private void notifyFlushRequest(Region region, boolean emergencyFlush) {
541     FlushType type = FlushType.NORMAL;
542     if (emergencyFlush) {
543       type = isAboveHighWaterMark() ? FlushType.ABOVE_HIGHER_MARK : FlushType.ABOVE_LOWER_MARK;
544     }
545     for (FlushRequestListener listener : flushRequestListeners) {
546       listener.flushRequested(type, region);
547     }
548   }
549 
550   private void wakeUpIfBlocking() {
551     synchronized (blockSignal) {
552       blockSignal.notifyAll();
553     }
554   }
555 
556   private boolean isTooManyStoreFiles(Region region) {
557 
558     // When compaction is disabled, the region is flushable
559     if (!region.getTableDesc().isCompactionEnabled()) {
560       return false;
561     }
562 
563     for (Store store : region.getStores()) {
564       if (store.hasTooManyStoreFiles()) {
565         return true;
566       }
567     }
568     return false;
569   }
570 
571   /**
572    * Check if the regionserver's memstore memory usage is greater than the
573    * limit. If so, flush regions with the biggest memstores until we're down
574    * to the lower limit. This method blocks callers until we're down to a safe
575    * amount of memstore consumption.
576    */
577   public void reclaimMemStoreMemory() {
578     TraceScope scope = Trace.startSpan("MemStoreFluser.reclaimMemStoreMemory");
579     if (isAboveHighWaterMark()) {
580       if (Trace.isTracing()) {
581         scope.getSpan().addTimelineAnnotation("Force Flush. We're above high water mark.");
582       }
583       long start = EnvironmentEdgeManager.currentTime();
584       synchronized (this.blockSignal) {
585         boolean blocked = false;
586         long startTime = 0;
587         boolean interrupted = false;
588         try {
589           while (isAboveHighWaterMark() && !server.isStopped()) {
590             if (!blocked) {
591               startTime = EnvironmentEdgeManager.currentTime();
592               LOG.info("Blocking updates on "
593                   + server.toString()
594                   + ": the global memstore size "
595                   + TraditionalBinaryPrefix.long2String(server.getRegionServerAccounting()
596                       .getGlobalMemstoreSize(), "", 1) + " is >= than blocking "
597                   + TraditionalBinaryPrefix.long2String(globalMemStoreLimit, "", 1) + " size");
598             }
599             blocked = true;
600             wakeupFlushThread();
601             try {
602               // we should be able to wait forever, but we've seen a bug where
603               // we miss a notify, so put a 5 second bound on it at least.
604               blockSignal.wait(5 * 1000);
605             } catch (InterruptedException ie) {
606               LOG.warn("Interrupted while waiting");
607               interrupted = true;
608             }
609             long took = EnvironmentEdgeManager.currentTime() - start;
610             LOG.warn("Memstore is above high water mark and block " + took + "ms");
611           }
612         } finally {
613           if (interrupted) {
614             Thread.currentThread().interrupt();
615           }
616         }
617 
618         if(blocked){
619           final long totalTime = EnvironmentEdgeManager.currentTime() - startTime;
620           if(totalTime > 0){
621             this.updatesBlockedMsHighWater.add(totalTime);
622           }
623           LOG.info("Unblocking updates for server " + server.toString());
624         }
625       }
626     } else if (isAboveLowWaterMark()) {
627       wakeupFlushThread();
628     }
629     scope.close();
630   }
631   @Override
632   public String toString() {
633     return "flush_queue="
634         + flushQueue.size();
635   }
636 
637   public String dumpQueue() {
638     StringBuilder queueList = new StringBuilder();
639     queueList.append("Flush Queue Queue dump:\n");
640     queueList.append("  Flush Queue:\n");
641     java.util.Iterator<FlushQueueEntry> it = flushQueue.iterator();
642 
643     while(it.hasNext()){
644       queueList.append("    "+it.next().toString());
645       queueList.append("\n");
646     }
647 
648     return queueList.toString();
649   }
650 
651   /**
652    * Register a MemstoreFlushListener
653    * @param listener
654    */
655   @Override
656   public void registerFlushRequestListener(final FlushRequestListener listener) {
657     this.flushRequestListeners.add(listener);
658   }
659 
660   /**
661    * Unregister the listener from MemstoreFlushListeners
662    * @param listener
663    * @return true when passed listener is unregistered successfully.
664    */
665   @Override
666   public boolean unregisterFlushRequestListener(final FlushRequestListener listener) {
667     return this.flushRequestListeners.remove(listener);
668   }
669 
670   /**
671    * Sets the global memstore limit to a new size.
672    * @param globalMemStoreSize
673    */
674   @Override
675   public void setGlobalMemstoreLimit(long globalMemStoreSize) {
676     this.globalMemStoreLimit = globalMemStoreSize;
677     this.globalMemStoreLimitLowMark =
678         (long) (this.globalMemStoreLimitLowMarkPercent * globalMemStoreSize);
679     reclaimMemStoreMemory();
680   }
681 
682   public long getMemoryLimit() {
683     return this.globalMemStoreLimit;
684   }
685 
686   interface FlushQueueEntry extends Delayed {
687   }
688 
689   /**
690    * Token to insert into the flush queue that ensures that the flusher does not sleep
691    */
692   static class WakeupFlushThread implements FlushQueueEntry {
693     @Override
694     public long getDelay(TimeUnit unit) {
695       return 0;
696     }
697 
698     @Override
699     public int compareTo(Delayed o) {
700       return -1;
701     }
702 
703     @Override
704     public int hashCode() {
705       return System.identityHashCode(this);
706     }
707 
708     @Override
709     public boolean equals(Object obj) {
710       return Objects.equals(this, obj);
711     }
712   }
713 
714   /**
715    * Datastructure used in the flush queue.  Holds region and retry count.
716    * Keeps tabs on how old this object is.  Implements {@link Delayed}.  On
717    * construction, the delay is zero. When added to a delay queue, we'll come
718    * out near immediately.  Call {@link #requeue(long)} passing delay in
719    * milliseconds before readding to delay queue if you want it to stay there
720    * a while.
721    */
722   static class FlushRegionEntry implements FlushQueueEntry {
723     private final Region region;
724 
725     private final long createTime;
726     private long whenToExpire;
727     private int requeueCount = 0;
728 
729     private boolean forceFlushAllStores;
730 
731     FlushRegionEntry(final Region r, boolean forceFlushAllStores) {
732       this.region = r;
733       this.createTime = EnvironmentEdgeManager.currentTime();
734       this.whenToExpire = this.createTime;
735       this.forceFlushAllStores = forceFlushAllStores;
736     }
737 
738     /**
739      * @param maximumWait
740      * @return True if we have been delayed > <code>maximumWait</code> milliseconds.
741      */
742     public boolean isMaximumWait(final long maximumWait) {
743       return (EnvironmentEdgeManager.currentTime() - this.createTime) > maximumWait;
744     }
745 
746     /**
747      * @return Count of times {@link #requeue(long)} was called; i.e this is
748      * number of times we've been requeued.
749      */
750     public int getRequeueCount() {
751       return this.requeueCount;
752     }
753 
754     /**
755      * @return whether we need to flush all stores.
756      */
757     public boolean isForceFlushAllStores() {
758       return forceFlushAllStores;
759     }
760 
761     /**
762      * @param when When to expire, when to come up out of the queue.
763      * Specify in milliseconds.  This method adds EnvironmentEdgeManager.currentTime()
764      * to whatever you pass.
765      * @return This.
766      */
767     public FlushRegionEntry requeue(final long when) {
768       this.whenToExpire = EnvironmentEdgeManager.currentTime() + when;
769       this.requeueCount++;
770       return this;
771     }
772 
773     @Override
774     public long getDelay(TimeUnit unit) {
775       return unit.convert(this.whenToExpire - EnvironmentEdgeManager.currentTime(),
776           TimeUnit.MILLISECONDS);
777     }
778 
779     @Override
780     public int compareTo(Delayed other) {
781       // Delay is compared first. If there is a tie, compare region's hash code
782       int ret = Long.valueOf(getDelay(TimeUnit.MILLISECONDS) -
783         other.getDelay(TimeUnit.MILLISECONDS)).intValue();
784       if (ret != 0) {
785         return ret;
786       }
787       FlushQueueEntry otherEntry = (FlushQueueEntry) other;
788       return hashCode() - otherEntry.hashCode();
789     }
790 
791     @Override
792     public String toString() {
793       return "[flush region "+Bytes.toStringBinary(region.getRegionInfo().getRegionName())+"]";
794     }
795 
796     @Override
797     public int hashCode() {
798       int hash = (int) getDelay(TimeUnit.MILLISECONDS);
799       return hash ^ region.hashCode();
800     }
801 
802    @Override
803     public boolean equals(Object obj) {
804       if (this == obj) {
805         return true;
806       }
807       if (obj == null || getClass() != obj.getClass()) {
808         return false;
809       }
810       FlushRegionEntry other = (FlushRegionEntry) obj;
811       if (!Bytes.equals(this.region.getRegionInfo().getRegionName(),
812           other.region.getRegionInfo().getRegionName())) {
813         return false;
814       }
815       return compareTo(other) == 0;
816     }
817   }
818 }