View Javadoc
1   /*
2    * Copyright 2012-2021 CodeLibs Project and the Others.
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,
13   * either express or implied. See the License for the specific language
14   * governing permissions and limitations under the License.
15   */
16  package org.codelibs.fess.util;
17  
18  import java.io.BufferedWriter;
19  import java.io.FileOutputStream;
20  import java.io.IOException;
21  import java.io.OutputStreamWriter;
22  import java.io.Writer;
23  import java.util.Map;
24  import java.util.function.Consumer;
25  
26  import org.apache.logging.log4j.LogManager;
27  import org.apache.logging.log4j.Logger;
28  import org.codelibs.core.exception.IORuntimeException;
29  import org.codelibs.fess.Constants;
30  
31  public class ThreadDumpUtil {
32      private static final Logger logger = LogManager.getLogger(ThreadDumpUtil.class);
33  
34      protected ThreadDumpUtil() {
35          // noop
36      }
37  
38      public static void printThreadDump() {
39          processThreadDump(logger::info);
40      }
41  
42      public static void printThreadDumpAsWarn() {
43          processThreadDump(logger::warn);
44      }
45  
46      public static void printThreadDumpAsError() {
47          processThreadDump(logger::error);
48      }
49  
50      public static void writeThreadDump(final String file) {
51          try (final Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), Constants.CHARSET_UTF_8))) {
52              processThreadDump(s -> {
53                  try {
54                      writer.write(s);
55                      writer.write('\n');
56                  } catch (final IOException e) {
57                      throw new IORuntimeException(e);
58                  }
59              });
60          } catch (final Exception e) {
61              logger.warn("Failed to write a thread dump to {}", file, e);
62          }
63      }
64  
65      public static void processThreadDump(final Consumer<String> writer) {
66          for (final Map.Entry<Thread, StackTraceElement[]> entry : Thread.getAllStackTraces().entrySet()) {
67              writer.accept("Thread: " + entry.getKey());
68              final StackTraceElement[] trace = entry.getValue();
69              for (final StackTraceElement element : trace) {
70                  writer.accept("\tat " + element);
71              }
72          }
73      }
74  }