KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > core > internal > runtime > PerformanceStatsProcessor


1 /*******************************************************************************
2  * Copyright (c) 2005, 2006 IBM Corporation and others.
3  * All rights reserved. This program and the accompanying materials
4  * are made available under the terms of the Eclipse Public License v1.0
5  * which accompanies this distribution, and is available at
6  * http://www.eclipse.org/legal/epl-v10.html
7  *
8  * Contributors:
9  * IBM - Initial API and implementation
10  *******************************************************************************/

11 package org.eclipse.core.internal.runtime;
12
13 import java.io.PrintWriter JavaDoc;
14 import java.util.ArrayList JavaDoc;
15 import java.util.HashMap JavaDoc;
16 import org.eclipse.core.runtime.*;
17 import org.eclipse.core.runtime.PerformanceStats.PerformanceListener;
18 import org.eclipse.core.runtime.jobs.Job;
19 import org.eclipse.osgi.framework.log.FrameworkLog;
20 import org.osgi.framework.BundleContext;
21 import org.osgi.framework.ServiceReference;
22
23 /**
24  * Processes, records, and performs notification of performance events
25  * that occur in the system.
26  */

27 public class PerformanceStatsProcessor extends Job {
28     private static final PerformanceStatsProcessor instance = new PerformanceStatsProcessor();
29
30     private static final long SCHEDULE_DELAY = 2000;
31
32     /**
33      * Events that have occurred but have not yet been broadcast.
34      */

35     private final ArrayList JavaDoc changes = new ArrayList JavaDoc();
36
37     /**
38      * Event failures that have occurred but have not yet been broadcast.
39      * Maps (PerformanceStats -> Long).
40      */

41     private final HashMap JavaDoc failures = new HashMap JavaDoc();
42
43     /**
44      * Event listeners.
45      */

46     private final org.eclipse.core.runtime.ListenerList listeners = new org.eclipse.core.runtime.ListenerList();
47
48     private PlatformLogWriter log;
49
50     /*
51      * @see PerformanceStats#addListener
52      */

53     public static void addListener(PerformanceListener listener) {
54         instance.listeners.add(listener);
55     }
56
57     /**
58      * Records the fact that an event occurred.
59      *
60      * @param stats The event that occurred
61      */

62     public static void changed(PerformanceStats stats) {
63         synchronized (instance) {
64             instance.changes.add(stats);
65         }
66         instance.schedule(SCHEDULE_DELAY);
67     }
68
69     /**
70      * Records the fact that an event failed.
71      *
72      * @param stats The event that occurred
73      * @param pluginId The id of the plugin that declared the blame object, or
74      * <code>null</code>
75      * @param elapsed The elapsed time for this failure
76      */

77     public static void failed(PerformanceStats stats, String JavaDoc pluginId, long elapsed) {
78         synchronized (instance) {
79             instance.failures.put(stats, new Long JavaDoc(elapsed));
80         }
81         instance.schedule(SCHEDULE_DELAY);
82         instance.logFailure(stats, pluginId, elapsed);
83     }
84
85     /*
86      * @see PerformanceStats#printStats(PrintWriter)
87      */

88     public static void printStats(PrintWriter JavaDoc out) {
89         /* gather totals */
90         long totalTime = 0;
91         int totalCount = 0;
92         PerformanceStats[] allStats = PerformanceStats.getAllStats();
93         for (int i = 0; i < allStats.length; i++) {
94             PerformanceStats stats = allStats[i];
95             totalTime += stats.getRunningTime();
96             totalCount += stats.getRunCount();
97         }
98         //dump stats
99
out.println("---------------------------------------------------------------"); //$NON-NLS-1$
100
for (int i = 0; i < allStats.length; i++) {
101             PerformanceStats stats = allStats[i];
102             out.print("Event: "); //$NON-NLS-1$
103
out.print(stats.getEvent());
104             out.print(" Blame: "); //$NON-NLS-1$
105
out.print(stats.getBlameString());
106             if (stats.getContext() != null) {
107                 out.print(" Context: "); //$NON-NLS-1$
108
out.print(stats.getContext());
109             }
110             out.println();
111
112             int runCount = stats.getRunCount();
113             if (runCount > 0) {
114                 out.print("Run count: "); //$NON-NLS-1$
115
out.print(Integer.toString(runCount));
116                 out.print(" ("); //$NON-NLS-1$
117
out.print(Integer.toString((int) (runCount * 100.0 / totalCount)));
118                 out.println(" % of total)"); //$NON-NLS-1$
119
}
120
121             long runTime = stats.getRunningTime();
122             if (runTime > 0) {
123                 out.print("Duration (ms): "); //$NON-NLS-1$
124
out.print(Long.toString(runTime));
125                 out.print(" ("); //$NON-NLS-1$
126
out.print(Integer.toString((int) (runTime * 100.0 / totalTime)));
127                 out.println(" % of total)"); //$NON-NLS-1$
128
}
129             out.println(""); //$NON-NLS-1$
130
}
131     }
132
133     /*
134      * @see PerformanceStats#removeListener
135      */

136     public static void removeListener(PerformanceListener listener) {
137         instance.listeners.remove(listener);
138     }
139
140     /**
141      * Private constructor to enforce singleton usage.
142      */

143     private PerformanceStatsProcessor() {
144         super("Performance Stats"); //$NON-NLS-1$
145
setSystem(true);
146         setPriority(DECORATE);
147         BundleContext context = PlatformActivator.getContext();
148         String JavaDoc filter = '(' + FrameworkLog.SERVICE_PERFORMANCE + '=' + Boolean.TRUE.toString() + ')';
149         ServiceReference[] references;
150         FrameworkLog perfLog = null;
151         try {
152             references = context.getServiceReferences(FrameworkLog.class.getName(), filter);
153             if (references != null && references.length > 0) {
154                 //just take the first matching service
155
perfLog = (FrameworkLog) context.getService(references[0]);
156                 //make sure correct location is set
157
IPath logLocation = Platform.getLogFileLocation();
158                 logLocation = logLocation.removeLastSegments(1).append("performance.log"); //$NON-NLS-1$
159
perfLog.setFile(logLocation.toFile(), false);
160             }
161         } catch (Exception JavaDoc e) {
162             IStatus error = new Status(IStatus.ERROR, Platform.PI_RUNTIME, 1, "Error loading performance log", e); //$NON-NLS-1$
163
InternalPlatform.getDefault().log(error);
164         }
165         //use the platform log if we couldn't create the performance log
166
if (perfLog == null)
167             perfLog = InternalPlatform.getDefault().getFrameworkLog();
168         log = new PlatformLogWriter(perfLog);
169     }
170
171     /**
172      * Logs performance event failures to the platform's performance log
173      */

174     private void logFailure(PerformanceStats stats, String JavaDoc pluginId, long elapsed) {
175         //may have failed to get the performance log service
176
if (log == null)
177             return;
178         if (pluginId == null)
179             pluginId = Platform.PI_RUNTIME;
180         String JavaDoc msg = "Performance failure: " + stats.getEvent() + " blame: " + stats.getBlameString() + " context: " + stats.getContext() + " duration: " + elapsed; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
181
log.logging(new Status(IStatus.WARNING, pluginId, 1, msg, new RuntimeException JavaDoc()), pluginId);
182     }
183
184     /*
185      * @see Job#run(IProgressMonitor)
186      */

187     protected IStatus run(IProgressMonitor monitor) {
188         PerformanceStats[] events;
189         PerformanceStats[] failedEvents;
190         Long JavaDoc[] failedTimes;
191         synchronized (this) {
192             events = (PerformanceStats[]) changes.toArray(new PerformanceStats[changes.size()]);
193             changes.clear();
194             failedEvents = (PerformanceStats[]) failures.keySet().toArray(new PerformanceStats[failures.size()]);
195             failedTimes = (Long JavaDoc[]) failures.values().toArray(new Long JavaDoc[failures.size()]);
196             failures.clear();
197         }
198
199         //notify performance listeners
200
Object JavaDoc[] toNotify = listeners.getListeners();
201         for (int i = 0; i < toNotify.length; i++) {
202             final PerformanceStats.PerformanceListener listener = ((PerformanceStats.PerformanceListener) toNotify[i]);
203             if (events.length > 0)
204                 listener.eventsOccurred(events);
205             for (int j = 0; j < failedEvents.length; j++)
206                 listener.eventFailed(failedEvents[j], failedTimes[j].longValue());
207         }
208         schedule(SCHEDULE_DELAY);
209         return Status.OK_STATUS;
210     }
211
212     /*
213      * @see Job#shouldRun()
214      */

215     public boolean shouldRun() {
216         return !changes.isEmpty() || !failures.isEmpty();
217     }
218 }
Popular Tags