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.io.Closeable;
22 import java.util.concurrent.Executor;
23 import java.util.concurrent.RejectedExecutionException;
24
25 import org.eclipse.jetty.util.log.Log;
26 import org.eclipse.jetty.util.log.Logger;
27 import org.eclipse.jetty.util.thread.ExecutionStrategy;
28
29 /**
30 * <p>Base class for strategies that need to execute a task by submitting it to an {@link Executor}.</p>
31 * <p>If the submission to the {@code Executor} is rejected (via a {@link RejectedExecutionException}),
32 * the task is tested whether it implements {@link Closeable}; if it does, then {@link Closeable#close()}
33 * is called on the task object.</p>
34 */
35 public abstract class ExecutingExecutionStrategy implements ExecutionStrategy
36 {
37 private static final Logger LOG = Log.getLogger(ExecutingExecutionStrategy.class);
38
39 private final Executor _executor;
40
41 protected ExecutingExecutionStrategy(Executor executor)
42 {
43 _executor=executor;
44 }
45
46 protected boolean execute(Runnable task)
47 {
48 try
49 {
50 _executor.execute(task);
51 return true;
52 }
53 catch(RejectedExecutionException e)
54 {
55 // If we cannot execute, then close the task and keep producing.
56 LOG.debug(e);
57 LOG.warn("Rejected execution of {}",task);
58 try
59 {
60 if (task instanceof Closeable)
61 ((Closeable)task).close();
62 }
63 catch (Exception x)
64 {
65 e.addSuppressed(x);
66 LOG.warn(e);
67 }
68 }
69 return false;
70 }
71 }