Must clean the buffer that holds Runnables that wait for execution and also drop all the executions that currently run
962749
public void doRecovery() {

//        Attempts to stop all actively executing tasks, halts the
//        processing of waiting tasks, and returns a list of the tasks
//        that were awaiting execution.
//
//        This method does not wait for actively executing tasks to
//        terminate.
//
//        There are no guarantees beyond best-effort attempts to stop
//        processing actively executing tasks.  For example, typical
//        implementations will cancel via {@link Thread#interrupt}, so any
//        task that fails to respond to interrupts may never terminate.
        try {
            synchronized (this) {
                executorService.shutdownNow(); //shutting down current running threads
                threadPoolVersion++;           //updating the thread pool version to a new one - so current running threads will exit
                logger.warn(
                        "Worker is in doRecovery(). Cleaning state and cancelling running tasks. It may take up to 30 seconds...");
            }

            boolean finished = executorService.awaitTermination(30, TimeUnit.SECONDS);

            if (finished) {
                logger.warn("Worker succeeded to cancel running tasks during doRecovery().");
            } else {
                logger.warn("Not all running tasks responded to cancel.");
            }
        } catch (InterruptedException ex) {/*ignore*/}

        mapOfRunningTasks.clear();

        //Make new executor
        executorService = new ThreadPoolExecutor(numberOfThreads,
                numberOfThreads,
                Long.MAX_VALUE, TimeUnit.NANOSECONDS,
                inBuffer,
                new WorkerThreadFactory((threadPoolVersion) + "_WorkerExecutionThread"));
    }
828038
public void flush() {
    for (Batch batch : batches.values()) {
      Collection<Batch> subbatches = batch.split();
      for (Batch miniBatch : subbatches) {
        threadPool.submit(miniBatch);
      }
    }
    batches.clear();
  }
499082
public static void cleanObsolete() {
        HandlerThreadFactory.getWriteLogThreadHandler().post(new Runnable() {
            @Override
            public void run() {
                long now = System.currentTimeMillis();
                File[] f = BlockCanaryInternals.getLogFiles();
                if (f != null && f.length > 0) {
                    synchronized (SAVE_DELETE_LOCK) {
                        for (File aF : f) {
                            if (now - aF.lastModified() > OBSOLETE_DURATION) {
                                aF.delete();
                            }
                        }
                    }
                }
            }
        });
    }
36571
public void clear() {
		//release a static buffer if possible
		if (_buffersToReuse != null && !_buffersToReuse.isEmpty()) {
			StaticBuffers.getInstance().releaseByteBuffer(BUFFER_KEY, _buffersToReuse.peek());
		} else if (!_buffers.isEmpty()) {
			StaticBuffers.getInstance().releaseByteBuffer(BUFFER_KEY, _buffers.get(0));
		}
		
		if (_buffersToReuse != null) {
			_buffersToReuse.clear();
		}
		_buffers.clear();
		_position = 0;
		_flushPosition = 0;
		_size = 0;
	}
195433
protected final void clear() {
        UnifiedDataPageX curr = getCurrentPage();

        for (int ii=0; ii<_buffers.length; ii++) {
            _buffers[ii] = null;
        }

        // curr is null when underlying stream is empty.
        if (curr != null)
        {
            _buffers[0] = curr;
            curr.reset(0);
        }

        _buffer_count = 0;
        _buffer_current = 0;
    }
205300
private void cleanup() {
    if (operation instanceof Command && log.isOpen()) {
      try {
        log.release(index);
      } catch (IllegalStateException e) {
      }
    }

    session.release();

    index = 0;
    session = null;
    instant = null;
    operation = null;

    pool.release(this);
  }
1337547
@Override
	public void cleanupConnection(ConnectionHandle oldHandle, ConnectionHandle newHandle) {
		this.threadFinalizableRefs.remove(oldHandle);
		this.threadWatch(newHandle);
	}
929232
void scheduleDrainBuffers() {
    if (drainStatus() >= PROCESSING_TO_IDLE) {
      return;
    }
    if (evictionLock.tryLock()) {
      try {
        int drainStatus = drainStatus();
        if (drainStatus >= PROCESSING_TO_IDLE) {
          return;
        }
        lazySetDrainStatus(PROCESSING_TO_IDLE);
        executor().execute(drainBuffersTask);
      } catch (Throwable t) {
        logger.log(Level.WARNING, "Exception thrown when submitting maintenance task", t);
        maintenance(/* ignored */ null);
      } finally {
        evictionLock.unlock();
      }
    }
  }
836955
def clean(self):
        
        for _, item in self.queue.items():
            if item['status'] in ['paused', 'running', 'stopping', 'killing']:
                item['status'] = 'queued'
                item['start'] = ''
                item['end'] = ''
333214
@Override
    public void postToMainThread(Runnable runnable) {
        if (mMainHandler == null) {
            synchronized (mLock) {
                if (mMainHandler == null) {
                    mMainHandler = new Handler(Looper.getMainLooper());
                }
            }
        }
        //noinspection ConstantConditions
        mMainHandler.post(runnable);
    }
284772
protected synchronized void flushBuffer(boolean chunkComplete,
      boolean keepPartialData) throws IOException {
    if (count != 0) {
      int chunkLen = count;
      count = 0;
      writeChecksumChunk(buf, 0, chunkLen, keepPartialData && !chunkComplete);
      if (!chunkComplete) {
        if (!keepPartialData) {
          bytesSentInChunk += chunkLen;
        } else {
          count = chunkLen;
        }
      } else {
        bytesSentInChunk = 0;
      }
    }
  }
1332946
def flush(self):
        
        if self.buffer is None:
            return
        data = self.buffer
        self.buffer = []
        for x in self.dests:
            yield from x.enqueue_task(self, *data)
2614
void drainBuffers() {
        // A mostly strict ordering is achieved by observing that each buffer
        // contains tasks in a weakly sorted order starting from the last drain.
        // The buffers can be merged into a sorted array in O(n) time by using
        // counting sort and chaining on a collision.

        // Moves the tasks into the output array, applies them, and updates the
        // marker for the starting order of the next drain.
        int maxTaskIndex = moveTasksFromBuffers(tasks);
        updateDrainedOrder(tasks, maxTaskIndex);
        runTasks(tasks, maxTaskIndex);
    }
34989
void performCleanUp(@Nullable Runnable task) {
    evictionLock.lock();
    try {
      maintenance(task);
    } finally {
      evictionLock.unlock();
    }
    if ((drainStatus() == REQUIRED) && (executor == ForkJoinPool.commonPool())) {
      scheduleDrainBuffers();
    }
  }
772332
public void purgeCache() {
        synchronized (users) {
            users.values().stream()
                    .map(Reference::get)
                    .filter(Objects::nonNull)
                    .map(Cleanupable.class::cast)
                    .forEach(Cleanupable::cleanup);
            users.clear();
        }
        userIdByRef.clear();
        servers.values().stream()
                .map(Cleanupable.class::cast)
                .forEach(Cleanupable::cleanup);
        servers.clear();
        channels.values().stream()
                .filter(Cleanupable.class::isInstance)
                .map(Cleanupable.class::cast)
                .forEach(Cleanupable::cleanup);
        channels.clear();
        unavailableServers.clear();
        customEmojis.clear();
        messages.clear();
        messageIdByRef.clear();
        timeOffset = null;
    }
958730
@Override
    public void recollect(W buffer) {
        if (queue.size() < preservedBufs) {
            long effectiveDrainDelay
                = drainDelay > 0 ? drainDelay : defaultDrainDelay;
            if (effectiveDrainDelay > 0) {
                // Enqueue
                buffer.clear();
                queue.add(buffer);
                Timer old = idleTimer.getAndSet(Components.schedule(this::drain,
                    Duration.ofMillis(effectiveDrainDelay)));
                if (old != null) {
                    old.cancel();
                }
                return;
            }
        }
        // Discard
        removeBuffer(buffer);
    }
390578
private void clear() {
        if (null != this._output) {
            for (int i = 0; i < this._output.length; i++) {
                if (null != this._output[i]) {
                    this._output[i].release();
                    this._output[i] = null;
                }
            }
        }
        this.outputIndex = 0;
        this.bufferedCount = 0;
        this.bytesWritten = 0L;
        this.setWriteListenerCallBack(null);
    }