@@ -70,12 +70,10 @@ def self.stat(all_stats_or_key = {})
70
70
module Profiler
71
71
def self . __setup__
72
72
@profiler ||= begin
73
- java . lang . Class . forName ( 'com.sun.management.GarbageCollectionNotificationInfo' )
74
-
75
- # class exists, proceed with GC notification version
76
- @profiler = NotifiedProfiler . new
77
- rescue java . lang . ClassNotFoundException
78
- @profiler = NormalProfiler . new
73
+ NotifiedProfiler . new!
74
+ # class exists and Java dependecies are also present, proceed with GC notification version
75
+ rescue NameError
76
+ NormalProfiler . new
79
77
end
80
78
end
81
79
@@ -115,35 +113,42 @@ def self.total_time
115
113
end
116
114
117
115
begin
118
- javax . management . NotificationListener # try to access
119
116
class NotifiedProfiler
120
117
HEADER = " ID Type Timestamp(sec) Before(kB) After(kB) Delta(kB) Heap(kB) GC Time(ms) \n "
121
118
FORMAT = "%5d %-20s %19.4f %13i %13i %12i %15i %20.10f\n "
122
119
123
- class GCListener
124
- include javax . management . NotificationListener
125
-
126
- def initialize
127
- @lines = [ ]
128
- end
129
-
130
- attr_accessor :lines
131
-
132
- def handleNotification ( notification , o )
133
- lines << notification
134
- end
135
-
136
- def clear
137
- lines . clear
138
- end
120
+ def self . new!
121
+ javax . management . NotificationListener # try to access
122
+ com . sun . management . GarbageCollectionNotificationInfo
123
+ new
139
124
end
140
125
141
126
def enabled?
142
127
@gc_listener != nil
143
128
end
144
129
145
130
def enable
146
- @gc_listener ||= GCListener . new
131
+ @gc_listener ||= begin
132
+ # delay JI class-loading, generate listener on first use :
133
+ gc_listener = Class . new do # GCListener
134
+ include javax . management . NotificationListener
135
+
136
+ def initialize
137
+ @lines = [ ]
138
+ end
139
+
140
+ attr_accessor :lines
141
+
142
+ def handleNotification ( notification , o )
143
+ lines << notification
144
+ end
145
+
146
+ def clear
147
+ lines . clear
148
+ end
149
+ end
150
+ gc_listener . new
151
+ end
147
152
java . lang . management . ManagementFactory . garbage_collector_mx_beans . each do |gc_bean |
148
153
gc_bean . add_notification_listener @gc_listener , nil , nil
149
154
end
@@ -233,6 +238,7 @@ def total_time
233
238
return duration / 1000.0
234
239
end
235
240
end
241
+ private_constant :NotifiedProfiler
236
242
rescue Exception
237
243
# ignore, leave it undefined
238
244
end
@@ -278,6 +284,7 @@ def total_time
278
284
( time - @start_time ) / 1000.0
279
285
end
280
286
end
287
+ private_constant :NormalProfiler
281
288
end
282
289
end
283
290
end
0 commit comments