Home | History | Annotate | Download | only in util
      1 /*
      2  * Copyright (C) 2012 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.internal.util;
     18 
     19 import android.os.Handler;
     20 
     21 import java.io.PrintWriter;
     22 import java.io.StringWriter;
     23 
     24 /**
     25  * Helper functions for dumping the state of system services.
     26  */
     27 public final class DumpUtils {
     28     private DumpUtils() {
     29     }
     30 
     31     /**
     32      * Helper for dumping state owned by a handler thread.
     33      *
     34      * Because the caller might be holding an important lock that the handler is
     35      * trying to acquire, we use a short timeout to avoid deadlocks.  The process
     36      * is inelegant but this function is only used for debugging purposes.
     37      */
     38     public static void dumpAsync(Handler handler, final Dump dump, PrintWriter pw,
     39             final String prefix, long timeout) {
     40         final StringWriter sw = new StringWriter();
     41         if (handler.runWithScissors(new Runnable() {
     42             @Override
     43             public void run() {
     44                 PrintWriter lpw = new FastPrintWriter(sw);
     45                 dump.dump(lpw, prefix);
     46                 lpw.close();
     47             }
     48         }, timeout)) {
     49             pw.print(sw.toString());
     50         } else {
     51             pw.println("... timed out");
     52         }
     53     }
     54 
     55     public interface Dump {
     56         void dump(PrintWriter pw, String prefix);
     57     }
     58 }
     59