public void stop() {

    try {
      flush();
    } catch (IOException e) {
      LOGGER.error("Error flushing", e);
    }
    try {
      close();
    } catch (IOException e) {
      LOGGER.error("Error closing", e);
    }
    try {
      backgroundFlushTask.shutdown();
      // Wait a while for existing tasks to terminate
      if (!backgroundFlushTask.awaitTermination(15, TimeUnit.SECONDS)) {
        backgroundFlushTask.shutdownNow(); // Cancel currently executing tasks
        // Wait a while for tasks to respond to being cancelled
        if (!backgroundFlushTask.awaitTermination(15, TimeUnit.SECONDS)) {
          LOGGER.error("Stream did not terminate");
        }
      }
    } catch (InterruptedException ie) {
      // (Re-)Cancel if current thread also interrupted
      backgroundFlushTask.shutdownNow();
      // Preserve interrupt status
      Thread.currentThread().interrupt();
    }
  }
 protected void flushIfNecessary() {
   long lastLatency = System.currentTimeMillis() - lastWrite.get();
   // Flush iff the size > 0 AND the size is divisible by 100 or the time between now and the last
   // flush is greater
   // than the maximum desired latency
   if (insertBatch.size() > 0
       && (insertBatch.size() % 100 == 0 || lastLatency > MAX_WRITE_LATENCY)) {
     try {
       flush();
     } catch (IOException e) {
       LOGGER.error("Error writing to Mongo", e);
     }
   }
 }