Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support a simple QueuedExecutor that can be drained (in the calling thread or a separate executor) #3986

Open
sanjaypujare opened this issue Aug 12, 2020 · 0 comments

Comments

@sanjaypujare
Copy link

While creating tests I thought it would be nice to have what I call a QueuedExecutor that can be supplied to code-under-test and then I can verify the tasks that are queued and optionally execute them in my thread or a separate executor. This would look something like:

  class QueuedExecutor implements Executor {
    /** A list of Runnables to be run in order. */
    private final Queue<Runnable> runQueue = new ConcurrentLinkedQueue<>();

    @Override
    public synchronized void execute(Runnable r) {
      runQueue.add(checkNotNull(r, "'r' must not be null."));
    }

    public void drain() {
        drain(MoreExecutors.directExecutor());
    }

    public void drain(Executor executor) {
      executor.execute(new Run() {
        Runnable r;
        synchronized(runQueue) {
          while ((r = runQueue.poll()) != null) {
            try {
              r.run();
            } catch (RuntimeException e) {
              // Log it and keep going.
              //...
            }
          }
        }
      });
    }
  }

And MoreExecutors can have a method to return one e.g. newQueuedExecutor Note that this is different from the behavior of MoreExecutors.newSequentialExecutor. I can create a PR to add this depending on feedback.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants