View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements. See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache license, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License. You may obtain a copy of the License at
8    *
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the license for the specific language governing permissions and
15   * limitations under the license.
16   */
17  package org.apache.logging.log4j.message;
18  
19  import java.io.InvalidObjectException;
20  import java.io.ObjectInputStream;
21  import java.io.Serializable;
22  import java.lang.management.ManagementFactory;
23  import java.lang.management.ThreadInfo;
24  import java.lang.management.ThreadMXBean;
25  import java.lang.reflect.Method;
26  import java.util.HashMap;
27  import java.util.Map;
28  
29  import org.apache.logging.log4j.util.StringBuilderFormattable;
30  import org.apache.logging.log4j.util.Strings;
31  
32  /**
33   * Captures information about all running Threads.
34   */
35  @AsynchronouslyFormattable
36  public class ThreadDumpMessage implements Message, StringBuilderFormattable {
37  
38      private static final long serialVersionUID = -1103400781608841088L;
39  
40      private static final ThreadInfoFactory FACTORY;
41  
42      private volatile Map<ThreadInformation, StackTraceElement[]> threads;
43  
44      private final String title;
45  
46      private String formattedMessage;
47  
48      static {
49          final Method[] methods = ThreadInfo.class.getMethods();
50          boolean basic = true;
51          for (final Method method : methods) {
52              if (method.getName().equals("getLockInfo")) {
53                  basic = false;
54                  break;
55              }
56          }
57          FACTORY = basic ? new BasicThreadInfoFactory() : new ExtendedThreadInfoFactory();
58      }
59  
60      /**
61       * Generate a ThreadDumpMessage with a title.
62       * @param title The title.
63       */
64      public ThreadDumpMessage(final String title) {
65          this.title = title == null ? Strings.EMPTY : title;
66          threads = FACTORY.createThreadInfo();
67      }
68  
69      private ThreadDumpMessage(final String formattedMsg, final String title) {
70          this.formattedMessage = formattedMsg;
71          this.title = title == null ? Strings.EMPTY : title;
72      }
73  
74      @Override
75      public String toString() {
76          return getFormattedMessage();
77      }
78  
79      /**
80       * Returns the ThreadDump in printable format.
81       * @return the ThreadDump suitable for logging.
82       */
83      @Override
84      public String getFormattedMessage() {
85          if (formattedMessage != null) {
86              return formattedMessage;
87          }
88          final StringBuilder sb = new StringBuilder(255);
89          formatTo(sb);
90          return sb.toString();
91      }
92  
93      @Override
94      public void formatTo(final StringBuilder sb) {
95          sb.append(title);
96          if (title.length() > 0) {
97              sb.append('\n');
98          }
99          for (final Map.Entry<ThreadInformation, StackTraceElement[]> entry : threads.entrySet()) {
100             final ThreadInformation info = entry.getKey();
101             info.printThreadInfo(sb);
102             info.printStack(sb, entry.getValue());
103             sb.append('\n');
104         }
105     }
106 
107     /**
108      * Returns the title.
109      * @return the title.
110      */
111     @Override
112     public String getFormat() {
113         return title == null ? Strings.EMPTY : title;
114     }
115 
116     /**
117      * Returns an array with a single element, a Map containing the ThreadInformation as the key.
118      * and the StackTraceElement array as the value;
119      * @return the "parameters" to this Message.
120      */
121     @Override
122     public Object[] getParameters() {
123         return null;
124     }
125 
126         /**
127      * Creates a ThreadDumpMessageProxy that can be serialized.
128      * @return a ThreadDumpMessageProxy.
129      */
130     protected Object writeReplace() {
131         return new ThreadDumpMessageProxy(this);
132     }
133 
134     private void readObject(final ObjectInputStream stream)
135         throws InvalidObjectException {
136         throw new InvalidObjectException("Proxy required");
137     }
138 
139     /**
140      * Proxy pattern used to serialize the ThreadDumpMessage.
141      */
142     private static class ThreadDumpMessageProxy implements Serializable {
143 
144         private static final long serialVersionUID = -3476620450287648269L;
145         private final String formattedMsg;
146         private final String title;
147 
148         ThreadDumpMessageProxy(final ThreadDumpMessage msg) {
149             this.formattedMsg = msg.getFormattedMessage();
150             this.title = msg.title;
151         }
152 
153         /**
154          * Returns a ThreadDumpMessage using the data in the proxy.
155          * @return a ThreadDumpMessage.
156          */
157         protected Object readResolve() {
158             return new ThreadDumpMessage(formattedMsg, title);
159         }
160     }
161 
162     /**
163      * Factory to create Thread information.
164      */
165     private interface ThreadInfoFactory {
166         Map<ThreadInformation, StackTraceElement[]> createThreadInfo();
167     }
168 
169     /**
170      * Factory to create basic thread information.
171      */
172     private static class BasicThreadInfoFactory implements ThreadInfoFactory {
173         @Override
174         public Map<ThreadInformation, StackTraceElement[]> createThreadInfo() {
175             final Map<Thread, StackTraceElement[]> map = Thread.getAllStackTraces();
176             final Map<ThreadInformation, StackTraceElement[]> threads =
177                 new HashMap<>(map.size());
178             for (final Map.Entry<Thread, StackTraceElement[]> entry : map.entrySet()) {
179                 threads.put(new BasicThreadInformation(entry.getKey()), entry.getValue());
180             }
181             return threads;
182         }
183     }
184 
185     /**
186      * Factory to create extended thread information.
187      */
188     private static class ExtendedThreadInfoFactory implements ThreadInfoFactory {
189         @Override
190         public Map<ThreadInformation, StackTraceElement[]> createThreadInfo() {
191             final ThreadMXBean bean = ManagementFactory.getThreadMXBean();
192             final ThreadInfo[] array = bean.dumpAllThreads(true, true);
193 
194             final Map<ThreadInformation, StackTraceElement[]>  threads =
195                 new HashMap<>(array.length);
196             for (final ThreadInfo info : array) {
197                 threads.put(new ExtendedThreadInformation(info), info.getStackTrace());
198             }
199             return threads;
200         }
201     }
202 
203     /**
204      * Always returns null.
205      *
206      * @return null
207      */
208     @Override
209     public Throwable getThrowable() {
210         return null;
211     }
212 }