From e06e6411c327e79f3efe48b13789ac4a467a5ea0 Mon Sep 17 00:00:00 2001 From: danfickle Date: Thu, 11 Feb 2021 13:34:43 +1100 Subject: [PATCH] #646 Add volatile where required for double checked locking Without volatile we can have the situation where thread 2 sees the value of initPending to be false and thus doesn't go through the synced section but sees loggers as not yet visible. This was rare and the test only failed on the first run on my machine before always passing. Hopefully, it should always work now. Fingers crossed. NOTE: Both of the changed classes use a version of the "double checked locking" pattern which the internet says requires volatile. --- .../src/main/java/com/openhtmltopdf/util/JDKXRLogger.java | 4 ++-- .../src/main/java/com/openhtmltopdf/util/XRLog.java | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/util/JDKXRLogger.java b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/util/JDKXRLogger.java index 932cd3dbd..ba44c8f1b 100644 --- a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/util/JDKXRLogger.java +++ b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/util/JDKXRLogger.java @@ -35,11 +35,11 @@ * https://github.com/danfickle/openhtmltopdf/wiki/Logging */ public class JDKXRLogger implements XRLogger { - private boolean initPending = true; + private volatile boolean initPending = true; // Keep a map of Loggers so they are not garbage collected // which makes them lose their settings we have applied. - private Map loggers; + private volatile Map loggers; private final boolean useParent; private final Level level; diff --git a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/util/XRLog.java b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/util/XRLog.java index 3bdc400d6..3219d6ba2 100644 --- a/openhtmltopdf-core/src/main/java/com/openhtmltopdf/util/XRLog.java +++ b/openhtmltopdf-core/src/main/java/com/openhtmltopdf/util/XRLog.java @@ -52,8 +52,8 @@ private static String registerLoggerByName(final String loggerName) { return loggerName; } - private static boolean initPending = true; - private static XRLogger loggerImpl; + private static volatile boolean initPending = true; + private static volatile XRLogger loggerImpl; private static volatile Boolean loggingEnabled;