1 /* 2 * Copyright 2015 The gRPC Authors 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package io.grpc.internal; 18 19 import com.google.common.base.Preconditions; 20 import java.util.ArrayDeque; 21 import java.util.concurrent.Executor; 22 import java.util.logging.Level; 23 import java.util.logging.Logger; 24 25 /** 26 * Executes a task directly in the calling thread, unless it's a reentrant call in which case the 27 * task is enqueued and executed once the calling task completes. 28 * 29 * <p>The {@code Executor} assumes that reentrant calls are rare and its fast path is thus 30 * optimized for that - avoiding queuing and additional object creation altogether. 31 * 32 * <p>This class is not thread-safe. 33 */ 34 class SerializeReentrantCallsDirectExecutor implements Executor { 35 36 private static final Logger log = 37 Logger.getLogger(SerializeReentrantCallsDirectExecutor.class.getName()); 38 39 private boolean executing; 40 // Lazily initialized if a reentrant call is detected. 41 private ArrayDeque<Runnable> taskQueue; 42 43 @Override execute(Runnable task)44 public void execute(Runnable task) { 45 Preconditions.checkNotNull(task, "'task' must not be null."); 46 if (!executing) { 47 executing = true; 48 try { 49 task.run(); 50 } catch (Throwable t) { 51 log.log(Level.SEVERE, "Exception while executing runnable " + task, t); 52 } finally { 53 if (taskQueue != null) { 54 completeQueuedTasks(); 55 } 56 executing = false; 57 } 58 } else { 59 enqueue(task); 60 } 61 } 62 completeQueuedTasks()63 private void completeQueuedTasks() { 64 Runnable task = null; 65 while ((task = taskQueue.poll()) != null) { 66 try { 67 task.run(); 68 } catch (Throwable t) { 69 // Log it and keep going 70 log.log(Level.SEVERE, "Exception while executing runnable " + task, t); 71 } 72 } 73 } 74 enqueue(Runnable r)75 private void enqueue(Runnable r) { 76 if (taskQueue == null) { 77 taskQueue = new ArrayDeque<Runnable>(4); 78 } 79 taskQueue.add(r); 80 } 81 } 82