JBR-9283 Enhance Window counters to provide statistics

Enhanced Window counters to provide statistics (using the new marlin StatDouble class), enhanced logging code to dump regularly (10s) window stats, added shutdown hook, bumpCounter() renamed to incrementCounter(), added addStat(window, name, value) used by MTLLayer to report blitTexture & nextDrawable timings (ms), use InnocuousThread for shutdown hooks, fixed D3DSurfaceData bumpCounter() usages to incrementCounter()
This commit is contained in:
bourgesl
2025-08-25 10:03:37 +02:00
parent 78e2a7bbd5
commit af437d9d61
11 changed files with 451 additions and 152 deletions

View File

@@ -33,7 +33,6 @@ import sun.lwawt.macosx.CFLayer;
import sun.util.logging.PlatformLogger;
import java.awt.Component;
import java.awt.GraphicsConfiguration;
import java.awt.Insets;
import java.awt.Window;
@@ -151,11 +150,25 @@ public final class MTLLayer extends CFLayer {
}
}
private final static String[] STAT_NAMES = new String[]{
"java2d.native.mtlLayer.drawInMTLContext", // type = 0
"java2d.native.mtlLayer.nextDrawable" // type = 1
};
private void addStat(int type, double value) {
// Called from the native code when this layer has been presented on screen
Component target = peer.getTarget();
if (target instanceof Window window) {
AWTAccessor.getWindowAccessor().addStat(window,
((type >= 0) && (type < STAT_NAMES.length)) ? STAT_NAMES[type] : "undefined", value);
}
}
private void countNewFrame() {
// Called from the native code when this layer has been presented on screen
Component target = peer.getTarget();
if (target instanceof Window window) {
AWTAccessor.getWindowAccessor().bumpCounter(window, "java2d.native.frames");
AWTAccessor.getWindowAccessor().incrementCounter(window, "java2d.native.frames");
}
}
@@ -165,7 +178,7 @@ public final class MTLLayer extends CFLayer {
// when those attempts are too frequent.
Component target = peer.getTarget();
if (target instanceof Window window) {
AWTAccessor.getWindowAccessor().bumpCounter(window, "java2d.native.framesDropped");
AWTAccessor.getWindowAccessor().incrementCounter(window, "java2d.native.framesDropped");
}
}
}

View File

@@ -71,6 +71,8 @@
- (void) stopRedraw:(MTLContext*)mtlc displayID:(jint)displayID force:(BOOL)force;
- (void) flushBuffer;
- (void) commitCommandBuffer:(MTLContext*)mtlc wait:(BOOL)waitUntilCompleted display:(BOOL)updateDisplay;
- (void) addStatCallback:(int)type value:(double)value;
- (void) countFramePresentedCallback;
- (void) countFrameDroppedCallback;
@end

View File

@@ -226,29 +226,32 @@ BOOL MTLLayer_isExtraRedrawEnabled() {
}
// Acquire CAMetalDrawable without blocking:
const CFTimeInterval beforeDrawableTime = (TRACE_DISPLAY) ? CACurrentMediaTime() : 0.0;
const CFTimeInterval beforeDrawableTime = CACurrentMediaTime();
const id<CAMetalDrawable> mtlDrawable = [self nextDrawable];
if (mtlDrawable == nil) {
J2dTraceLn(J2D_TRACE_VERBOSE, "MTLLayer.blitTexture: nextDrawable is null");
return;
}
const CFTimeInterval nextDrawableTime = (TRACE_DISPLAY) ? CACurrentMediaTime() : 0.0;
const CFTimeInterval nextDrawableTime = CACurrentMediaTime();
const CFTimeInterval nextDrawableLatency = (nextDrawableTime - beforeDrawableTime);
// rolling mean weight (lerp):
static const NSTimeInterval a = 0.25;
#if TRACE_DISPLAY_ON
const CFTimeInterval nextDrawableLatency = (nextDrawableTime - beforeDrawableTime);
if (nextDrawableLatency > 0.0) {
[self addStatCallback:1 value:1000.0 * nextDrawableLatency]; // See MTLLayer.STAT_NAMES[1]
#if TRACE_DISPLAY_ON
self.avgNextDrawableTime = nextDrawableLatency * a + self.avgNextDrawableTime * (1.0 - a);
}
J2dRlsTraceLn(J2D_TRACE_VERBOSE,
"[%.6lf] MTLLayer_blitTexture: drawable(%d) presented"
" - nextDrawableLatency = %.3lf ms - average = %.3lf ms",
CACurrentMediaTime(), mtlDrawable.drawableID,
1000.0 * nextDrawableLatency, 1000.0 * self.avgNextDrawableTime
);
J2dRlsTraceLn(J2D_TRACE_VERBOSE,
"[%.6lf] MTLLayer_blitTexture: drawable(%d) presented"
" - nextDrawableLatency = %.3lf ms - average = %.3lf ms",
CACurrentMediaTime(), mtlDrawable.drawableID,
1000.0 * nextDrawableLatency, 1000.0 * self.avgNextDrawableTime
);
#endif
}
// Keep Fence from now:
releaseFence = NO;
@@ -389,8 +392,15 @@ BOOL MTLLayer_isExtraRedrawEnabled() {
return;
}
const CFTimeInterval beforeMethod = CACurrentMediaTime();
(*env)->CallVoidMethod(env, javaLayerLocalRef, jm_drawInMTLContext);
CHECK_EXCEPTION();
const CFTimeInterval drawInMTLContextLatency = (CACurrentMediaTime() - beforeMethod);
if (drawInMTLContextLatency > 0.0) {
[self addStatCallback:0 value:1000.0 * drawInMTLContextLatency]; // See MTLLayer.STAT_NAMES[0]
}
(*env)->DeleteLocalRef(env, javaLayerLocalRef);
}
@@ -516,6 +526,20 @@ BOOL MTLLayer_isExtraRedrawEnabled() {
}
}
- (void) addStatCallback:(int)type value:(double)value {
// attach the current thread to the JVM if necessary, and get an env
JNIEnv* env = [ThreadUtilities getJNIEnvUncached];
GET_MTL_LAYER_CLASS();
DECLARE_METHOD(jm_addStatFrame, jc_JavaLayer, "addStat", "(ID)V");
jobject javaLayerLocalRef = (*env)->NewLocalRef(env, self.javaLayer);
if (javaLayerLocalRef != NULL) {
(*env)->CallVoidMethod(env, javaLayerLocalRef, jm_addStatFrame, (jint)type, (jdouble)value);
CHECK_EXCEPTION();
(*env)->DeleteLocalRef(env, javaLayerLocalRef);
}
}
- (void) countFrameDroppedCallback {
// attach the current thread to the JVM if necessary, and get an env
JNIEnv* env = [ThreadUtilities getJNIEnvUncached];

View File

@@ -34,7 +34,6 @@ import java.awt.event.WindowFocusListener;
import java.awt.event.WindowListener;
import java.awt.event.WindowStateListener;
import java.awt.geom.Path2D;
import java.awt.geom.Point2D;
import java.awt.im.InputContext;
import java.awt.image.BufferStrategy;
import java.awt.peer.ComponentPeer;
@@ -44,6 +43,7 @@ import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OptionalDataException;
import java.io.PrintStream;
import java.io.Serial;
import java.io.Serializable;
import java.lang.annotation.Native;
@@ -53,12 +53,15 @@ import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.EventListener;
import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.Map;
import java.util.HashMap;
import java.util.Objects;
import java.util.ResourceBundle;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import java.util.Vector;
import java.util.concurrent.atomic.AtomicBoolean;
@@ -69,11 +72,14 @@ import javax.accessibility.AccessibleState;
import javax.accessibility.AccessibleStateSet;
import com.jetbrains.exported.JBRApi;
import jdk.internal.misc.InnocuousThread;
import sun.awt.AWTAccessor;
import sun.awt.AppContext;
import sun.awt.DebugSettings;
import sun.awt.SunToolkit;
import sun.awt.util.IdentityArrayList;
import sun.awt.util.ThreadGroupUtils;
import sun.java2d.marlin.stats.StatDouble;
import sun.java2d.pipe.Region;
import sun.util.logging.PlatformLogger;
@@ -1153,45 +1159,51 @@ public class Window extends Container implements Accessible {
}
void doDispose() {
class DisposeAction implements Runnable {
public void run() {
disposing = true;
try {
// Check if this window is the fullscreen window for the
// device. Exit the fullscreen mode prior to disposing
// of the window if that's the case.
GraphicsDevice gd = getGraphicsConfiguration().getDevice();
if (gd.getFullScreenWindow() == Window.this) {
gd.setFullScreenWindow(null);
}
final class DisposeAction implements Runnable {
public void run() {
final Window window = Window.this;
Object[] ownedWindowArray;
synchronized(ownedWindowList) {
ownedWindowArray = new Object[ownedWindowList.size()];
ownedWindowList.copyInto(ownedWindowArray);
}
for (int i = 0; i < ownedWindowArray.length; i++) {
Window child = (Window) (((WeakReference)
(ownedWindowArray[i])).get());
if (child != null) {
child.disposeImpl();
// dump stats if needed:
AWTAccessor.getWindowAccessor().dumpStats(window, true, null);
disposing = true;
try {
// Check if this window is the fullscreen window for the
// device. Exit the fullscreen mode prior to disposing
// of the window if that's the case.
GraphicsDevice gd = getGraphicsConfiguration().getDevice();
if (gd.getFullScreenWindow() == window) {
gd.setFullScreenWindow(null);
}
}
hide();
beforeFirstShow = true;
removeNotify();
synchronized (inputContextLock) {
if (inputContext != null) {
inputContext.dispose();
inputContext = null;
Object[] ownedWindowArray;
synchronized(ownedWindowList) {
ownedWindowArray = new Object[ownedWindowList.size()];
ownedWindowList.copyInto(ownedWindowArray);
}
for (int i = 0; i < ownedWindowArray.length; i++) {
Window child = (Window) (((WeakReference)
(ownedWindowArray[i])).get());
if (child != null) {
child.disposeImpl();
}
}
hide();
beforeFirstShow = true;
removeNotify();
synchronized (inputContextLock) {
if (inputContext != null) {
inputContext.dispose();
inputContext = null;
}
}
clearCurrentFocusCycleRootOnHide();
} finally {
disposing = false;
}
clearCurrentFocusCycleRootOnHide();
} finally {
disposing = false;
}
}
}
boolean fireWindowClosedEvent = isDisplayable();
DisposeAction action = new DisposeAction();
if (EventQueue.isDispatchThread()) {
@@ -4160,8 +4172,36 @@ public class Window extends Container implements Accessible {
return value;
}
private final static String STATS_ALL_SUFFIX = ".all";
private final static String SYSTEM_PROPERTY_COUNTERS;
private final static boolean USE_COUNTERS;
private final static boolean TRACE_ALL_COUNTERS;
private final static boolean TRACE_STD_ERR;
private final static int TRACE_CAPACITY;
private final static boolean TRACE_COUNTERS = true;
private final static boolean DUMP_STATS = true;
// thread dump interval (ms)
static final long DUMP_INTERVAL = 10 * 1000L;
private static PrintStream getTraceStdStream() {
// get live std stream:
return TRACE_STD_ERR ? System.err : System.out;
}
static {
String counters = System.getProperty("awt.window.counters");
SYSTEM_PROPERTY_COUNTERS = System.getProperty("awt.window.counters");
USE_COUNTERS = (SYSTEM_PROPERTY_COUNTERS != null);
TRACE_ALL_COUNTERS = USE_COUNTERS && (Objects.equals(SYSTEM_PROPERTY_COUNTERS, "")
|| Objects.equals(SYSTEM_PROPERTY_COUNTERS, "stderr")
|| Objects.equals(SYSTEM_PROPERTY_COUNTERS, "stdout"));
TRACE_STD_ERR = USE_COUNTERS && SYSTEM_PROPERTY_COUNTERS.contains("stderr");
TRACE_CAPACITY = USE_COUNTERS ? 8 : 0;
AWTAccessor.setWindowAccessor(new AWTAccessor.WindowAccessor() {
public void updateWindow(Window window) {
@@ -4198,100 +4238,201 @@ public class Window extends Container implements Accessible {
public boolean countersEnabled(Window w) {
// May want to selectively enable or disable counters per window
return counters != null;
return USE_COUNTERS;
}
public void bumpCounter(Window w, String counterName) {
Objects.requireNonNull(w);
Objects.requireNonNull(counterName);
private final static long NANO_IN_SEC = java.util.concurrent.TimeUnit.SECONDS.toNanos(1);
PerfCounter newCounter;
long curTimeNanos = System.nanoTime();
synchronized (w.perfCounters) {
newCounter = w.perfCounters.compute(counterName, (k, v) ->
v == null
? new PerfCounter(curTimeNanos, 1L)
: new PerfCounter(curTimeNanos, v.value + 1));
}
PerfCounter prevCounter;
synchronized (w.perfCountersPrev) {
prevCounter = w.perfCountersPrev.putIfAbsent(counterName, newCounter);
}
if (prevCounter != null) {
long nanosInSecond = java.util.concurrent.TimeUnit.SECONDS.toNanos(1);
long timeDeltaNanos = curTimeNanos - prevCounter.updateTimeNanos;
if (timeDeltaNanos > nanosInSecond) {
long valPerSecond = (long) ((double) (newCounter.value - prevCounter.value)
* nanosInSecond / timeDeltaNanos);
boolean traceAllCounters = Objects.equals(counters, "")
|| Objects.equals(counters, "stdout")
|| Objects.equals(counters, "stderr");
boolean traceEnabled = traceAllCounters || (counters != null && counters.contains(counterName));
if (traceEnabled) {
if (counters.contains("stderr")) {
System.err.println(counterName + " per second: " + valPerSecond);
} else {
System.out.println(counterName + " per second: " + valPerSecond);
}
}
if (perfLog.isLoggable(PlatformLogger.Level.FINE)) {
perfLog.fine(counterName + " per second: " + valPerSecond);
public void incrementCounter(final Window w, final String counterName) {
if (USE_COUNTERS) {
Objects.requireNonNull(w);
Objects.requireNonNull(counterName);
final long curTimeNanos = System.nanoTime();
// use try-catch to avoid throwing runtime exception to native JNI callers!
try {
PerfCounter newCounter, prevCounter;
synchronized (w.perfCounters) {
newCounter = w.perfCounters.compute(counterName, (_, v) ->
v == null
? new PerfCounter(curTimeNanos, 1L)
: new PerfCounter(curTimeNanos, v.value + 1));
}
synchronized (w.perfCountersPrev) {
w.perfCountersPrev.put(counterName, newCounter);
prevCounter = w.perfCountersPrev.putIfAbsent(counterName, newCounter);
}
if (prevCounter != null) {
final long timeDeltaNanos = curTimeNanos - prevCounter.updateTimeNanos;
if (timeDeltaNanos > NANO_IN_SEC) {
final double valPerSecond = (double) (newCounter.value - prevCounter.value)
* NANO_IN_SEC / timeDeltaNanos;
synchronized (w.perfCountersPrev) {
w.perfCountersPrev.put(counterName, newCounter);
}
addStat(w, counterName, valPerSecond);
if (TRACE_COUNTERS) {
dumpCounter(counterName, valPerSecond);
}
}
}
} catch (RuntimeException re) {
perfLog.severe("incrementCounter: failed", re);
}
}
}
public void addStat(final Window w, final String statName, final double value) {
if (USE_COUNTERS && Double.isFinite(value)) {
Objects.requireNonNull(w);
Objects.requireNonNull(statName);
// use try-catch to avoid throwing runtime exception to native JNI callers!
try {
synchronized (w.perfStats) {
StatDouble stat = w.perfStats.computeIfAbsent(statName, StatDouble::new);
stat.add(value);
stat = w.perfStats.computeIfAbsent(statName + STATS_ALL_SUFFIX, StatDouble::new);
stat.add(value);
}
} catch (RuntimeException re) {
perfLog.severe("addStat: failed", re);
}
}
}
public long getCounter(final Window w, final String counterName) {
if (USE_COUNTERS) {
Objects.requireNonNull(w);
Objects.requireNonNull(counterName);
synchronized (w.perfCounters) {
PerfCounter counter = w.perfCounters.get(counterName);
return counter != null ? counter.value : -1L;
}
}
return -1L;
}
public double getCounterPerSecond(final Window w, final String counterName) {
if (USE_COUNTERS) {
Objects.requireNonNull(w);
Objects.requireNonNull(counterName);
PerfCounter newCounter, prevCounter;
synchronized (w.perfCounters) {
newCounter = w.perfCounters.get(counterName);
}
synchronized (w.perfCountersPrev) {
prevCounter = w.perfCountersPrev.get(counterName);
}
if (newCounter != null && prevCounter != null) {
final long timeDeltaNanos = newCounter.updateTimeNanos - prevCounter.updateTimeNanos;
// Note that this time delta will usually be above one second.
if (timeDeltaNanos > 0L) {
return (double) (newCounter.value - prevCounter.value) * NANO_IN_SEC / timeDeltaNanos;
}
}
}
return Double.NaN;
}
public void dumpStats(final Window w, final boolean reset, StringBuilder sb) {
if (USE_COUNTERS) {
synchronized (w.perfStats) {
boolean header = false;
for (final StatDouble stat : w.perfStats.values()) {
if (stat.shouldLog()) {
final boolean traceEnabled = TRACE_ALL_COUNTERS || SYSTEM_PROPERTY_COUNTERS.contains(stat.name);
if (!header) {
header = true;
doLog(String.format("* Window['%s'@%s]:",
(w instanceof Frame ? ((Frame) w).getTitle() : ""),
Integer.toHexString(System.identityHashCode(w))),
traceEnabled);
}
// format:
if (sb == null) {
sb = new StringBuilder(128);
}
sb.setLength(0);
sb.append(" - ");
stat.toString(sb);
doLog(sb.toString(), traceEnabled);
if (reset && !stat.name.endsWith(STATS_ALL_SUFFIX)) {
stat.reset();
} else {
stat.updateLastLogCount();
}
}
}
}
}
}
public long getCounter(Window w, String counterName) {
Objects.requireNonNull(w);
Objects.requireNonNull(counterName);
synchronized (w.perfCounters) {
PerfCounter counter = w.perfCounters.get(counterName);
return counter != null ? counter.value : -1L;
private static void dumpCounter(final String counterName, final double valPerSecond) {
if (USE_COUNTERS) {
doLog(String.format("%s per second: %.2f", counterName, valPerSecond),
TRACE_ALL_COUNTERS || SYSTEM_PROPERTY_COUNTERS.contains(counterName));
}
}
public long getCounterPerSecond(Window w, String counterName) {
Objects.requireNonNull(w);
Objects.requireNonNull(counterName);
PerfCounter newCounter;
PerfCounter prevCounter;
synchronized (w.perfCounters) {
newCounter = w.perfCounters.get(counterName);
private static void doLog(final String msg, final boolean traceEnabled) {
if (traceEnabled) {
getTraceStdStream().println(msg);
}
synchronized (w.perfCountersPrev) {
prevCounter = w.perfCountersPrev.get(counterName);
if (perfLog.isLoggable(PlatformLogger.Level.FINE)) {
perfLog.fine(msg);
}
if (newCounter != null && prevCounter != null) {
long timeDeltaNanos = newCounter.updateTimeNanos - prevCounter.updateTimeNanos;
// Note that this time delta will usually be above one second.
if (timeDeltaNanos > 0) {
long nanosInSecond = java.util.concurrent.TimeUnit.SECONDS.toNanos(1);
long valPerSecond = (long) ((double) (newCounter.value - prevCounter.value)
* nanosInSecond / timeDeltaNanos);
return valPerSecond;
}
}
return -1;
}
}); // WindowAccessor
if (USE_COUNTERS) {
final Runnable dumper = new Runnable() {
private final static StringBuilder sb = new StringBuilder(128);
@Override
public void run() {
getTraceStdStream().printf("--- WindowStats dump at: %s ---\n", new java.util.Date());
final AWTAccessor.WindowAccessor windowAccessor = AWTAccessor.getWindowAccessor();
for (Window window : Window.getWindows()) {
// dump stats if needed:
windowAccessor.dumpStats(window, true, sb);
}
getTraceStdStream().println("-----");
}
};
final Thread hook = InnocuousThread.newSystemThread("WindowStatsHook", dumper);
hook.setDaemon(true);
hook.setContextClassLoader(null);
Runtime.getRuntime().addShutdownHook(hook);
if (DUMP_STATS) {
final Timer statTimer = new Timer("WindowStats");
statTimer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
dumper.run();
}
}, DUMP_INTERVAL, DUMP_INTERVAL);
}
}
} // static
// a window doesn't need to be updated in the Z-order.
@Override
void updateZOrder() {}
private record PerfCounter(Long updateTimeNanos, Long value) {}
private record PerfCounter(long updateTimeNanos, long value) {}
private transient final Map<String, PerfCounter> perfCounters = new HashMap<>(4);
private transient final Map<String, PerfCounter> perfCountersPrev = new HashMap<>(4);
private transient final HashMap<String, PerfCounter> perfCounters = (USE_COUNTERS) ? new HashMap<>(TRACE_CAPACITY) : null;
private transient final HashMap<String, PerfCounter> perfCountersPrev = (USE_COUNTERS) ? new HashMap<>(TRACE_CAPACITY) : null;
private transient final LinkedHashMap<String, StatDouble> perfStats = (USE_COUNTERS) ? new LinkedHashMap<>(TRACE_CAPACITY) : null;
} // class Window

View File

@@ -27,10 +27,7 @@ package javax.swing;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.awt.image.VolatileImage;
import java.awt.peer.WindowPeer;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
@@ -42,14 +39,12 @@ import sun.java2d.SunGraphicsEnvironment;
import com.sun.java.swing.SwingUtilities3;
import java.awt.geom.AffineTransform;
import java.util.stream.Collectors;
import sun.java2d.SunGraphics2D;
import sun.java2d.pipe.Region;
import sun.swing.SwingAccessor;
import sun.swing.SwingUtilities2;
import sun.swing.SwingUtilities2.RepaintListener;
import java.util.stream.Collectors;
/**
* This class manages repaint requests, allowing the number
@@ -723,7 +718,7 @@ public class RepaintManager
.filter(Objects::nonNull)
.distinct()
.forEach(w -> AWTAccessor.getWindowAccessor()
.bumpCounter(w, "swing.RepaintManager.updateWindows"));
.incrementCounter(w, "swing.RepaintManager.updateWindows"));
if (Toolkit.getDefaultToolkit() instanceof SunToolkit sunToolkit &&
sunToolkit.needUpdateWindow()) {
@@ -742,14 +737,14 @@ public class RepaintManager
for (Window window : windows) {
AWTAccessor.getWindowAccessor().updateWindow(window);
AWTAccessor.getWindowAccessor().bumpCounter(window, "swing.RepaintManager.updateWindows");
AWTAccessor.getWindowAccessor().incrementCounter(window, "swing.RepaintManager.updateWindows");
}
} else {
dirtyComponents.keySet().stream()
.map(c -> c instanceof Window w ? w : SwingUtilities.getWindowAncestor(c))
.filter(Objects::nonNull)
.forEach(w -> AWTAccessor.getWindowAccessor()
.bumpCounter(w, "swing.RepaintManager.updateWindows"));
.incrementCounter(w, "swing.RepaintManager.updateWindows"));
}
}

View File

@@ -37,7 +37,6 @@ import java.awt.event.InputEvent;
import java.awt.event.InvocationEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.geom.Point2D;
import java.awt.image.BufferStrategy;
import java.awt.peer.ComponentPeer;
@@ -329,10 +328,15 @@ public final class AWTAccessor {
*/
Window[] getOwnedWindows(Window w);
/* JBR Window counters API */
boolean countersEnabled(Window w);
void bumpCounter(Window w, String counterName);
void incrementCounter(Window w, String counterName);
void addStat(Window w, String statName, double value);
long getCounter(Window w, String counterName);
long getCounterPerSecond(Window w, String counterName);
double getCounterPerSecond(Window w, String counterName);
void dumpStats(Window w, boolean reset, StringBuilder sb);
}
/**

View File

@@ -28,6 +28,8 @@ package sun.java2d.marlin;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentLinkedQueue;
import jdk.internal.misc.InnocuousThread;
import jdk.internal.ref.CleanerFactory;
import sun.java2d.marlin.ArrayCacheConst.CacheStats;
import static sun.java2d.marlin.MarlinUtils.logInfo;
@@ -383,16 +385,8 @@ public final class RendererStats implements MarlinConst {
= new ConcurrentLinkedQueue<>();
private RendererStatsHolder() {
final Thread hook = new Thread(
MarlinUtils.getRootThreadGroup(),
new Runnable() {
@Override
public void run() {
dump();
}
},
"MarlinStatsHook"
);
final Thread hook = InnocuousThread.newSystemThread("MarlinStatsHook", () -> dump());
hook.setDaemon(true);
hook.setContextClassLoader(null);
Runtime.getRuntime().addShutdownHook(hook);

View File

@@ -0,0 +1,128 @@
/*
* Copyright (c) 2025, Oracle and/or its affiliates. All rights reserved.
* Copyright 2025 JetBrains s.r.o.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package sun.java2d.marlin.stats;
import static sun.java2d.marlin.stats.StatLong.trimTo3Digits;
/**
* Statistics on double values
*/
public final class StatDouble {
// rolling mean weight (lerp):
private final static double EMA_ALPHA = 0.25;
private final static double EMA_ONE_MINUS_ALPHA = 1.0 - EMA_ALPHA;
public final String name;
private long count, lastLogCount;
private double min, max, mean, ema_mean = 0.0, squaredError;
public StatDouble(final String name) {
this.name = name;
reset();
}
public void reset() {
count = 0L;
lastLogCount = 0L;
min = Double.POSITIVE_INFINITY;
max = Double.NEGATIVE_INFINITY;
mean = 0.0;
// skip ema_mean = 0.0;
squaredError = 0.0;
}
public void add(final double val) {
count++;
if (val < min) {
min = val;
}
if (val > max) {
max = val;
}
// Exponential smoothing (EMA):
ema_mean = EMA_ALPHA * val + EMA_ONE_MINUS_ALPHA * ema_mean;
// Welford's algorithm:
final double oldMean = mean;
mean += (val - mean) / count;
squaredError += (val - mean) * (val - oldMean);
}
public boolean shouldLog() {
return (count > lastLogCount);
}
public void updateLastLogCount() {
this.lastLogCount = this.count;
}
public long count() {
return count;
}
public double min() {
return (count != 0L) ? min : Double.NaN;
}
public double max() {
return (count != 0L) ? max : Double.NaN;
}
public double mean() {
return (count != 0L) ? mean : Double.NaN;
}
public double ema() {
return (count != 0L) ? ema_mean : Double.NaN;
}
public double variance() {
return (count != 0L) ? (squaredError / (count - 1L)) : Double.NaN;
}
public double stddev() {
return (count != 0L) ? Math.sqrt(variance()) : Double.NaN;
}
public double total() {
return (count != 0L) ? (mean() * count) : Double.NaN;
}
@Override
public String toString() {
return toString(new StringBuilder(128)).toString();
}
public StringBuilder toString(final StringBuilder sb) {
sb.append(name).append('[').append(count);
sb.append("] sum: ").append(trimTo3Digits(total()));
sb.append(" avg: ").append(trimTo3Digits(mean()));
sb.append(" stddev: ").append(trimTo3Digits(stddev()));
sb.append(" ema: ").append(trimTo3Digits(ema()));
sb.append(" [").append(trimTo3Digits(min())).append(" - ").append(trimTo3Digits(max())).append("]");
return sb;
}
}

View File

@@ -31,20 +31,18 @@ package sun.java2d.marlin.stats;
public class StatLong {
public final String name;
public long count = 0L;
public long sum = 0L;
public long min = Integer.MAX_VALUE;
public long max = Integer.MIN_VALUE;
public long count, sum, min, max;
public StatLong(final String name) {
this.name = name;
reset();
}
public void reset() {
count = 0L;
sum = 0L;
min = Integer.MAX_VALUE;
max = Integer.MIN_VALUE;
min = Long.MAX_VALUE;
max = Long.MIN_VALUE;
}
public void add(final int val) {
@@ -78,7 +76,7 @@ public class StatLong {
sb.append(name).append('[').append(count);
sb.append("] sum: ").append(sum).append(" avg: ");
sb.append(trimTo3Digits(((double) sum) / count));
sb.append(" [").append(min).append(" | ").append(max).append("]");
sb.append(" [").append(min).append(" - ").append(max).append("]");
return sb;
}
@@ -89,7 +87,7 @@ public class StatLong {
* @return double value with only 3 decimal digits
*/
public static double trimTo3Digits(final double value) {
return ((long) (1e3d * value)) / 1e3d;
return Double.isFinite(value) ? ((long) (1e3d * value)) / 1e3d : Double.NaN;
}
}

View File

@@ -199,7 +199,7 @@ public class WLSMSurfaceData extends SurfaceData implements WLSurfaceDataExt, WL
private void countNewFrame() {
// Called from the native code when this surface data has been sent to the Wayland server
if (target instanceof Window window) {
AWTAccessor.getWindowAccessor().bumpCounter(window, "java2d.native.frames");
AWTAccessor.getWindowAccessor().incrementCounter(window, "java2d.native.frames");
}
}
@@ -208,7 +208,7 @@ public class WLSMSurfaceData extends SurfaceData implements WLSurfaceDataExt, WL
// the Wayland server, but that attempt was not successful. This can happen, for example,
// when those attempts are too frequent.
if (target instanceof Window window) {
AWTAccessor.getWindowAccessor().bumpCounter(window, "java2d.native.framesDropped");
AWTAccessor.getWindowAccessor().incrementCounter(window, "java2d.native.framesDropped");
}
}

View File

@@ -831,11 +831,11 @@ public class D3DSurfaceData extends SurfaceData implements AccelSurface {
if (sd.getPeer().getTarget() instanceof Window window) {
switch (D3DRenderQueue.getFramePresentedStatus()) {
case 1:
AWTAccessor.getWindowAccessor().bumpCounter(window, "java2d.native.framesPresentRequested");
AWTAccessor.getWindowAccessor().incrementCounter(window, "java2d.native.framesPresentRequested");
break;
case 0:
default:
AWTAccessor.getWindowAccessor().bumpCounter(window, "java2d.native.framesPresentFailed");
AWTAccessor.getWindowAccessor().incrementCounter(window, "java2d.native.framesPresentFailed");
}
}
}