You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@causeway.apache.org by da...@apache.org on 2024/06/21 15:33:32 UTC

(causeway) branch maintenance-branch updated (0f66f74512 -> c2843151d0)

This is an automated email from the ASF dual-hosted git repository.

danhaywood pushed a change to branch maintenance-branch
in repository https://gitbox.apache.org/repos/asf/causeway.git


    from 0f66f74512 CAUSEWAY-3770: uses PASS_THROUGH in some other locations
     add 9bb4ee61ea CAUSEWAY-3781 : polishing log messages
     add 04816c577b CAUSEWAY-3788: sketches API changes to MetricsService, introduces Changes within ECTD
     add 6f5d216424 CAUSEWAY-3788: makes detailed metrics configurable
     add 1a4ea189c6 CAUSEWAY-3888 : updates PageRenderLogger to print out metrics.
     new c2843151d0 CAUSEWAY-3795 : fixes destroy callback

The 1 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails.  The revisions
listed as "add" were already present in the repository and have only
been added to this reference.


Summary of changes:
 .../applib/services/metrics/MetricsService.java    |  48 +++++--
 .../services/publishing/log/PageRenderLogger.java  |  34 ++++-
 .../core/config/CausewayConfiguration.java         |  22 ++++
 .../specloader/specimpl/ObjectActionDefault.java   |   5 +-
 .../specloader/specimpl/ObjectActionMixedIn.java   |   5 +-
 .../command/CommandExecutorServiceDefault.java     |   5 +-
 .../transaction/scope/StackedTransactionScope.java |  96 +++++++++-----
 .../changetracking/EntityChangeTrackerDefault.java | 145 +++++++++++++--------
 8 files changed, 247 insertions(+), 113 deletions(-)


(causeway) 01/01: CAUSEWAY-3795 : fixes destroy callback

Posted by da...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

danhaywood pushed a commit to branch maintenance-branch
in repository https://gitbox.apache.org/repos/asf/causeway.git

commit c2843151d0e5adc1c2909316db031a466704810a
Author: Dan Haywood <da...@haywood-associates.co.uk>
AuthorDate: Fri Jun 21 14:03:22 2024 +0100

    CAUSEWAY-3795 : fixes destroy callback
    
    ... and so no need to clear out resources before then.
---
 .../transaction/scope/StackedTransactionScope.java | 96 ++++++++++++++--------
 .../changetracking/EntityChangeTrackerDefault.java | 42 ++++------
 2 files changed, 76 insertions(+), 62 deletions(-)

diff --git a/core/transaction/src/main/java/org/apache/causeway/core/transaction/scope/StackedTransactionScope.java b/core/transaction/src/main/java/org/apache/causeway/core/transaction/scope/StackedTransactionScope.java
index 768ee2bee4..a30b1b8816 100644
--- a/core/transaction/src/main/java/org/apache/causeway/core/transaction/scope/StackedTransactionScope.java
+++ b/core/transaction/src/main/java/org/apache/causeway/core/transaction/scope/StackedTransactionScope.java
@@ -15,10 +15,13 @@
  */
 package org.apache.causeway.core.transaction.scope;
 
+import lombok.val;
+
 import java.util.HashMap;
 import java.util.LinkedHashMap;
 import java.util.Map;
 import java.util.Stack;
+import java.util.UUID;
 
 import org.springframework.beans.factory.ObjectFactory;
 import org.springframework.beans.factory.config.Scope;
@@ -32,11 +35,11 @@ public class StackedTransactionScope implements Scope {
     @Override
     public Object get(final String name, final ObjectFactory<?> objectFactory) {
 
-        Object key = currentKeyOnTransactionStack();
+        val transactionNestingLevelForThisThread = currentTransactionNestingLevelForThisThread();
 
-        ScopedObjectsHolder scopedObjects = (ScopedObjectsHolder) TransactionSynchronizationManager.getResource(key);
+        ScopedObjectsHolder scopedObjects = (ScopedObjectsHolder) TransactionSynchronizationManager.getResource(currentTransactionNestingLevelForThisThread());
         if (scopedObjects == null) {
-            scopedObjects = new ScopedObjectsHolder();
+            scopedObjects = new ScopedObjectsHolder(transactionNestingLevelForThisThread);
             if (TransactionSynchronizationManager.isSynchronizationActive()) {
                 // this happen when TransactionSynchronization#afterCompletion is called.
                 // it's a catch-22 : we use TransactionSynchronization as a resource to hold the scoped objects,
@@ -48,7 +51,7 @@ public class StackedTransactionScope implements Scope {
             } else {
                 scopedObjects.registered = false;
             }
-            TransactionSynchronizationManager.bindResource(key, scopedObjects);
+            TransactionSynchronizationManager.bindResource(transactionNestingLevelForThisThread, scopedObjects);
         } else {
             if (TransactionSynchronizationManager.isSynchronizationActive()) {
                 // it's possible that this already-existing scopedObject was added when a synchronization wasn't active
@@ -76,8 +79,8 @@ public class StackedTransactionScope implements Scope {
     @Override
     @Nullable
     public Object remove(final String name) {
-        Object key = currentKeyOnTransactionStack();
-        ScopedObjectsHolder scopedObjects = (ScopedObjectsHolder) TransactionSynchronizationManager.getResource(key);
+        val currentTransactionNestingLevel = currentTransactionNestingLevelForThisThread();
+        ScopedObjectsHolder scopedObjects = (ScopedObjectsHolder) TransactionSynchronizationManager.getResource(currentTransactionNestingLevel);
         if (scopedObjects != null) {
             scopedObjects.destructionCallbacks.remove(name);
             return scopedObjects.scopedInstances.remove(name);
@@ -88,21 +91,34 @@ public class StackedTransactionScope implements Scope {
 
     @Override
     public void registerDestructionCallback(final String name, final Runnable callback) {
-        ScopedObjectsHolder scopedObjects = (ScopedObjectsHolder) TransactionSynchronizationManager.getResource(this);
+        ScopedObjectsHolder scopedObjects = (ScopedObjectsHolder) TransactionSynchronizationManager.getResource(currentTransactionNestingLevelForThisThread());
         if (scopedObjects != null) {
             scopedObjects.destructionCallbacks.put(name, callback);
         }
     }
 
-    private static final ThreadLocal<Stack<Object>> transactionStackThreadLocal = ThreadLocal.withInitial(() -> {
-        Stack<Object> stack = new Stack<>();
-        stack.push(new Object());
+    /**
+     * Holds a unique id for each nested transaction within the current thread.
+     *
+     * <p>
+     * We chose to use a UUID rather than a integer, say, because an integer might be mis-interpreted as having a
+     * sequence. All we really need is a unique object, and a UUID is a little easier to work with (debug with) than
+     * using an anonymous <code>new Object()</code>.
+     * </p>
+     */
+    private static final ThreadLocal<Stack<UUID>> transactionNestingLevelThreadLocal = ThreadLocal.withInitial(() -> {
+        Stack<UUID> stack = new Stack<>();
+        stack.push(UUID.randomUUID());
         return stack;
     });
 
     /**
-     * Maintains a stack of keys, where the top-most is the key managed by {@link TransactionSynchronizationManager}
-     * holding the {@link ScopedObjectsHolder} for the current transaction.
+     * Maintains a stack of keys representing nested transactions, where the top-most is the key managed by
+     * {@link TransactionSynchronizationManager} holding the {@link ScopedObjectsHolder} for the current transaction.
+     *
+     * <p>
+     * The keys themselves are {@link UUID}s, having no meaning in themselves other than their identity as the key
+     * into a hashmap.
      *
      * <p>
      * If a transaction is suspended, then the {@link CleanupSynchronization#suspend() suspend} callback is used
@@ -110,42 +126,40 @@ public class StackedTransactionScope implements Scope {
      * {@link org.apache.causeway.applib.annotation.TransactionScope transaction-scope}d beans of the suspended
      * transaction) from {@link TransactionSynchronizationManager}.  As transaction-scoped beans are then resolved,
      * they will be associated with the new key.
-     * </p>
      *
      * <p>
      * Conversely, when a transaction is resumed, then the process is reversed; the old key is popped, and the previous
      * key is rebound to the {@link TransactionSynchronizationManager}, meaning that the previous transaction's
      * {@link org.apache.causeway.applib.annotation.TransactionScope transaction-scope}d beans are brought back.
-     * </p>
      *
-     * @see #currentKeyOnTransactionStack()
-     * @see #pushNewKeyOntoTransactionStack()
-     * @see #popOldKeyFromTransactionStack()
-     * @see #transactionStackThreadLocal
+     * @see #currentTransactionNestingLevelForThisThread()
+     * @see #pushToNewTransactionNestingLevelForThisThread()
+     * @see #popToPreviousTransactionNestingLevelForThisThread()
+     * @see #transactionNestingLevelThreadLocal
      */
-    private static Stack<Object> transactionStack() {
-        return transactionStackThreadLocal.get();
+    private static Stack<UUID> transactionNestingLevelForThread() {
+        return transactionNestingLevelThreadLocal.get();
     }
 
     /**
-     * @see #transactionStack()
+     * @see #transactionNestingLevelForThread()
      */
-    private Object currentKeyOnTransactionStack() {
-        return transactionStack().peek();
+    private UUID currentTransactionNestingLevelForThisThread() {
+        return transactionNestingLevelForThread().peek();
     }
 
     /**
-     * @see #transactionStack()
+     * @see #transactionNestingLevelForThread()
      */
-    private static void pushNewKeyOntoTransactionStack() {
-        transactionStack().push(new Object());
+    private static void pushToNewTransactionNestingLevelForThisThread() {
+        transactionNestingLevelForThread().push(UUID.randomUUID());
     }
 
     /**
-     * @see #transactionStack()
+     * @see #transactionNestingLevelForThread()
      */
-    private static void popOldKeyFromTransactionStack() {
-        transactionStack().pop();
+    private static void popToPreviousTransactionNestingLevelForThisThread() {
+        transactionNestingLevelForThread().pop();
     }
 
 
@@ -167,6 +181,13 @@ public class StackedTransactionScope implements Scope {
      */
     static class ScopedObjectsHolder {
 
+        private final UUID transactionUuid;
+
+        ScopedObjectsHolder(UUID transactionUuid) {
+            this.transactionUuid = transactionUuid;
+        }
+
+
         final Map<String, Object> scopedInstances = new HashMap<>();
         final Map<String, Runnable> destructionCallbacks = new LinkedHashMap<>();
 
@@ -182,6 +203,12 @@ public class StackedTransactionScope implements Scope {
          * </p>
          */
         private boolean registered = false;
+
+        public String toString() {
+            return String.format(
+                    "uuid: %s, registered: %s, scopedInstances.size(): %d, destructionCallbacks.size(): %d",
+                    transactionUuid, registered, scopedInstances.size(), destructionCallbacks.size());
+        }
     }
 
 
@@ -195,19 +222,20 @@ public class StackedTransactionScope implements Scope {
 
         @Override
         public void suspend() {
-            TransactionSynchronizationManager.unbindResource(currentKeyOnTransactionStack());
-            pushNewKeyOntoTransactionStack();  // subsequent calls to obtain a @TransactionScope'd bean will be against this key
+            val transactionNestingLevelForThisThread = currentTransactionNestingLevelForThisThread();
+            TransactionSynchronizationManager.unbindResource(transactionNestingLevelForThisThread);
+            pushToNewTransactionNestingLevelForThisThread();  // subsequent calls to obtain a @TransactionScope'd bean will be against this key
         }
 
         @Override
         public void resume() {
-            popOldKeyFromTransactionStack(); // the now-completed transaction's @TransactionScope'd beans are no longer required, and will be GC'd.
-            TransactionSynchronizationManager.bindResource(currentKeyOnTransactionStack(), this.scopedObjects);
+            popToPreviousTransactionNestingLevelForThisThread(); // the now-completed transaction's @TransactionScope'd beans are no longer required, and will be GC'd.
+            TransactionSynchronizationManager.bindResource(currentTransactionNestingLevelForThisThread(), this.scopedObjects);
         }
 
         @Override
         public void afterCompletion(final int status) {
-            TransactionSynchronizationManager.unbindResourceIfPossible(StackedTransactionScope.this.currentKeyOnTransactionStack());
+            TransactionSynchronizationManager.unbindResourceIfPossible(StackedTransactionScope.this.currentTransactionNestingLevelForThisThread());
             for (Runnable callback : this.scopedObjects.destructionCallbacks.values()) {
                 callback.run();
             }
diff --git a/persistence/commons/src/main/java/org/apache/causeway/persistence/commons/integration/changetracking/EntityChangeTrackerDefault.java b/persistence/commons/src/main/java/org/apache/causeway/persistence/commons/integration/changetracking/EntityChangeTrackerDefault.java
index 4aec4eac70..c022e1b08a 100644
--- a/persistence/commons/src/main/java/org/apache/causeway/persistence/commons/integration/changetracking/EntityChangeTrackerDefault.java
+++ b/persistence/commons/src/main/java/org/apache/causeway/persistence/commons/integration/changetracking/EntityChangeTrackerDefault.java
@@ -270,14 +270,18 @@ implements
             log.debug("EntityChangeTrackerDefault.destroy xactn={} interactionId={} thread={}", transactionCounter.get(), interactionId, Thread.currentThread().getName());
         }
 
-        resetState();
-    }
+        enlistedPropertyChangeRecordsById.clear();
+        changes.clear();
+
+        changeKindByEnlistedAdapter.clear();
+        numberEntitiesLoaded.reset();
+        entityChangeEventCount.reset();
 
-    private void resetState() {
-        resetState(numberEntitiesLoaded, entityChangeEventCount);
+        persistentChangesEncountered.set(false);
     }
 
 
+
     /**
      * @implNote sets a lock on the {@code enlistedPropertyChangeRecordsById} {@link Map}
      *      until given {@code runnable} completes<p>
@@ -322,33 +326,15 @@ implements
 
     @Override
     public void beforeCompletion() {
-        try {
-            _Xray.publish(this, interactionProviderProvider);
-
-            log.debug("about to publish entity changes");
-
-            // we memoize the property changes to (hopefully) avoid ConcurrentModificationExceptions with ourselves later
-            memoizeChangesIfRequired();
+        _Xray.publish(this, interactionProviderProvider);
 
-            entityPropertyChangePublisher.publishChangedProperties();
-            entityChangesPublisher.publishChangingEntities(this);
+        log.debug("about to publish entity changes");
 
-        } finally {
-            log.debug("purging entity change records");
+        // we memoize the property changes to (hopefully) avoid ConcurrentModificationExceptions with ourselves later
+        memoizeChangesIfRequired();
 
-            resetState(entityChangeEventCount, numberEntitiesLoaded);
-        }
-    }
-
-    private void resetState(LongAdder entityChangeEventCount, LongAdder numberEntitiesLoaded) {
-        enlistedPropertyChangeRecordsById.clear();
-        changes.clear();
-
-        changeKindByEnlistedAdapter.clear();
-        entityChangeEventCount.reset();
-        numberEntitiesLoaded.reset();
-
-        persistentChangesEncountered.set(false);
+        entityPropertyChangePublisher.publishChangedProperties();
+        entityChangesPublisher.publishChangingEntities(this);
     }
 
     private void enableCommandPublishing() {