1 /* 2 * Copyright (C) 2016 The Android Open Source Project 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 com.android.server.telecom; 18 19 /** 20 * Encapsulates session logging in a Runnable to reduce code duplication when continuing subsessions 21 * in a handler/thread. 22 */ 23 public abstract class Runnable { 24 25 private Session mSubsession; 26 private final String mSubsessionName; 27 private final Object mLock; 28 private final java.lang.Runnable mRunnable = new java.lang.Runnable() { 29 @Override 30 public void run() { 31 synchronized (mLock) { 32 try { 33 Log.continueSession(mSubsession, mSubsessionName); 34 loggedRun(); 35 } finally { 36 if (mSubsession != null) { 37 Log.endSession(); 38 mSubsession = null; 39 } 40 } 41 } 42 } 43 }; 44 45 /** 46 * Creates a new Telecom Runnable that incorporates Session Logging into it. Useful for carrying 47 * Logging Sessions through different threads as well as through handlers. 48 * @param subsessionName The name that will be used in the Logs to mark this Session 49 * @param lock The synchronization lock that will be used to lock loggedRun(). 50 */ Runnable(String subsessionName, Object lock)51 public Runnable(String subsessionName, Object lock) { 52 if (lock == null) { 53 mLock = new Object(); 54 } else { 55 mLock = lock; 56 } 57 mSubsessionName = subsessionName; 58 } 59 60 /** 61 * Return the runnable that will be canceled in the handler queue. 62 * @return Runnable object to cancel. 63 */ getRunnableToCancel()64 public final java.lang.Runnable getRunnableToCancel() { 65 return mRunnable; 66 } 67 68 /** 69 * Creates a Runnable and a logging subsession that can be used in a handler/thread. Be sure to 70 * call cancel() if this session is never going to be run (removed from a handler queue, for 71 * for example). 72 * @return A Java Runnable that can be used in a handler queue or thread. 73 */ prepare()74 public java.lang.Runnable prepare() { 75 cancel(); 76 mSubsession = Log.createSubsession(); 77 return mRunnable; 78 } 79 80 /** 81 * This method is used to clean up the active session if the Runnable gets removed from a 82 * handler and is never run. 83 */ cancel()84 public void cancel() { 85 synchronized (mLock) { 86 Log.cancelSubsession(mSubsession); 87 mSubsession = null; 88 } 89 } 90 91 /** 92 * The method that will be run in the handler/thread. This method will be called with mLock 93 * held. 94 */ loggedRun()95 abstract public void loggedRun(); 96 97 } 98