View Javadoc

1   //
2   //  ========================================================================
3   //  Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
4   //  ------------------------------------------------------------------------
5   //  All rights reserved. This program and the accompanying materials
6   //  are made available under the terms of the Eclipse Public License v1.0
7   //  and Apache License v2.0 which accompanies this distribution.
8   //
9   //      The Eclipse Public License is available at
10  //      http://www.eclipse.org/legal/epl-v10.html
11  //
12  //      The Apache License v2.0 is available at
13  //      http://www.opensource.org/licenses/apache2.0.php
14  //
15  //  You may elect to redistribute this code under either of these licenses.
16  //  ========================================================================
17  //
18  
19  package org.eclipse.jetty.util.thread.strategy;
20  
21  import java.util.concurrent.Executor;
22  
23  import org.eclipse.jetty.util.thread.ExecutionStrategy;
24  
25  /**
26   * <p>A strategy where the caller thread iterates over task production, submitting each
27   * task to an {@link Executor} for execution.</p>
28   */
29  public class ProduceConsume implements ExecutionStrategy, Runnable
30  {
31      private final Producer _producer;
32      private final Executor _executor;
33  
34      public ProduceConsume(Producer producer, Executor executor)
35      {
36          this._producer = producer;
37          this._executor = executor;
38      }
39  
40      @Override
41      public void execute()
42      {
43          // Iterate until we are complete.
44          while (true)
45          {
46              // Produce a task.
47              Runnable task = _producer.produce();
48  
49              if (task == null)
50                  break;
51  
52              // run the task.
53              task.run();
54          }
55      }
56  
57      @Override
58      public void dispatch()
59      {
60          _executor.execute(this);
61      }
62  
63      @Override
64      public void run()
65      {
66          execute();
67      }
68  }