Rename opendaylight.mdsal.binding.runtime.spi
[yangtools.git] / data / yang-data-tree-ri / src / main / java / org / opendaylight / yangtools / yang / data / tree / impl / InMemoryDataTreeModification.java
index 365f26c82efd8d41cd0051ad00012aab995aa7fd..d01b15c0b3bf08e36516f62b2a608425be560a79 100644 (file)
@@ -11,9 +11,11 @@ import static com.google.common.base.Preconditions.checkArgument;
 import static com.google.common.base.Preconditions.checkState;
 import static java.util.Objects.requireNonNull;
 
+import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
 import java.lang.invoke.MethodHandles;
 import java.lang.invoke.VarHandle;
 import java.util.Optional;
+import org.eclipse.jdt.annotation.Nullable;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
@@ -25,32 +27,35 @@ import org.opendaylight.yangtools.yang.data.tree.api.SchemaValidationFailedExcep
 import org.opendaylight.yangtools.yang.data.tree.impl.node.TreeNode;
 import org.opendaylight.yangtools.yang.data.tree.impl.node.Version;
 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
-import org.opendaylight.yangtools.yang.model.api.EffectiveModelContextProvider;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-final class InMemoryDataTreeModification extends AbstractCursorAware implements CursorAwareDataTreeModification,
-        EffectiveModelContextProvider {
+final class InMemoryDataTreeModification extends AbstractCursorAware implements CursorAwareDataTreeModification {
     private static final Logger LOG = LoggerFactory.getLogger(InMemoryDataTreeModification.class);
 
-    private final RootApplyStrategy strategyTree;
-    private final InMemoryDataTreeSnapshot snapshot;
-    private final ModifiedNode rootNode;
-    private final Version version;
+    private static final byte STATE_OPEN    = 0;
+    private static final byte STATE_SEALING = 1;
+    private static final byte STATE_SEALED  = 2;
 
-    private static final VarHandle SEALED;
+    private static final VarHandle STATE;
 
     static {
         try {
-            SEALED = MethodHandles.lookup().findVarHandle(InMemoryDataTreeModification.class, "sealed", int.class);
+            STATE = MethodHandles.lookup().findVarHandle(InMemoryDataTreeModification.class, "state", byte.class);
         } catch (NoSuchFieldException | IllegalAccessException e) {
             throw new ExceptionInInitializerError(e);
         }
     }
 
-    // All access needs to go through this handle
+    private final RootApplyStrategy strategyTree;
+    private final InMemoryDataTreeSnapshot snapshot;
+    private final ModifiedNode rootNode;
+    private final Version version;
+
+    // All access needs to go through STATE
     @SuppressWarnings("unused")
-    private volatile int sealed;
+    @SuppressFBWarnings(value = "UUF_UNUSED_FIELD", justification = "https://github.com/spotbugs/spotbugs/issues/2749")
+    private volatile byte state;
 
     InMemoryDataTreeModification(final InMemoryDataTreeSnapshot snapshot,
             final RootApplyStrategy resolver) {
@@ -67,7 +72,7 @@ final class InMemoryDataTreeModification extends AbstractCursorAware implements
          * node in modification and in data tree (if successfully
          * committed) will be same and will not change.
          */
-        version = snapshot.getRootNode().getSubtreeVersion().next();
+        version = snapshot.getRootNode().subtreeVersion().next();
     }
 
     ModifiedNode getRootModification() {
@@ -83,28 +88,27 @@ final class InMemoryDataTreeModification extends AbstractCursorAware implements
     }
 
     @Override
-    public EffectiveModelContext getEffectiveModelContext() {
-        return snapshot.getEffectiveModelContext();
+    public EffectiveModelContext modelContext() {
+        return snapshot.modelContext();
     }
 
     @Override
     public void write(final YangInstanceIdentifier path, final NormalizedNode data) {
-        checkSealed();
+        checkOpen();
         checkIdentifierReferencesData(path, data);
         resolveModificationFor(path).write(data);
     }
 
     @Override
     public void merge(final YangInstanceIdentifier path, final NormalizedNode data) {
-        checkSealed();
+        checkOpen();
         checkIdentifierReferencesData(path, data);
         resolveModificationFor(path).merge(data, version);
     }
 
     @Override
     public void delete(final YangInstanceIdentifier path) {
-        checkSealed();
-
+        checkOpen();
         resolveModificationFor(path).delete();
     }
 
@@ -123,24 +127,18 @@ final class InMemoryDataTreeModification extends AbstractCursorAware implements
         final var terminalPath = terminal.getKey();
 
         final var result = resolveSnapshot(terminalPath, terminal.getValue());
-        if (result.isPresent()) {
-            final var data = result.orElseThrow().getData();
-            return NormalizedNodes.findNode(terminalPath, data, path);
-        }
-
-        return Optional.empty();
+        return result == null ? Optional.empty() : NormalizedNodes.findNode(terminalPath, result.data(), path);
     }
 
     @SuppressWarnings("checkstyle:illegalCatch")
-    private Optional<? extends TreeNode> resolveSnapshot(final YangInstanceIdentifier path,
-            final ModifiedNode modification) {
+    private @Nullable TreeNode resolveSnapshot(final YangInstanceIdentifier path, final ModifiedNode modification) {
         final var potentialSnapshot = modification.getSnapshot();
         if (potentialSnapshot != null) {
-            return potentialSnapshot;
+            return potentialSnapshot.orElse(null);
         }
 
         try {
-            return resolveModificationStrategy(path).apply(modification, modification.getOriginal(), version);
+            return resolveModificationStrategy(path).apply(modification, modification.original(), version);
         } catch (Exception e) {
             LOG.error("Could not create snapshot for {}:{}", path, modification, e);
             throw e;
@@ -191,10 +189,6 @@ final class InMemoryDataTreeModification extends AbstractCursorAware implements
         return OperationWithModification.from(operation, modification);
     }
 
-    private void checkSealed() {
-        checkState(!isSealed(), "Data Tree is sealed. No further modifications allowed.");
-    }
-
     @Override
     public String toString() {
         return "MutableDataTree [modification=" + rootNode + "]";
@@ -214,12 +208,11 @@ final class InMemoryDataTreeModification extends AbstractCursorAware implements
          * have same version each time this method is called.
          */
         final var originalSnapshotRoot = snapshot.getRootNode();
-        final var tempRoot = getStrategy().apply(rootNode, Optional.of(originalSnapshotRoot), version);
-        checkState(tempRoot.isPresent(), "Data tree root is not present, possibly removed by previous modification");
-
-        final var tempTree = new InMemoryDataTreeSnapshot(snapshot.getEffectiveModelContext(), tempRoot.orElseThrow(),
-            strategyTree);
-        return tempTree.newModification();
+        final var newRoot = getStrategy().apply(rootNode, originalSnapshotRoot, version);
+        if (newRoot == null) {
+            throw new IllegalStateException("Data tree root is not present, possibly removed by previous modification");
+        }
+        return new InMemoryDataTreeSnapshot(snapshot.modelContext(), newRoot, strategyTree).newModification();
     }
 
     Version getVersion() {
@@ -228,7 +221,14 @@ final class InMemoryDataTreeModification extends AbstractCursorAware implements
 
     boolean isSealed() {
         // a quick check, synchronizes *only* on the sealed field
-        return (int) SEALED.getAcquire(this) != 0;
+        return (byte) STATE.getAcquire(this) == STATE_SEALED;
+    }
+
+    private void checkOpen() {
+        final var local = (byte) STATE.getAcquire(this);
+        if (local != STATE_OPEN) {
+            throw new IllegalStateException("Data Tree is sealed. No further modifications allowed in state " + local);
+        }
     }
 
     private static void applyChildren(final DataTreeModificationCursor cursor, final ModifiedNode node) {
@@ -300,14 +300,20 @@ final class InMemoryDataTreeModification extends AbstractCursorAware implements
 
     @Override
     public void ready() {
-        // We want a full CAS with setVolatile() memory semantics, as we want to force happen-before
-        // for everything, including whatever user code works.
-        final boolean wasRunning = SEALED.compareAndSet(this, 0, 1);
-        checkState(wasRunning, "Attempted to seal an already-sealed Data Tree.");
+        // We want a full CAS with setVolatile() memory semantics, as we want to force happen-before for everything,
+        // including whatever user code works.
+        if (!STATE.compareAndSet(this, STATE_OPEN, STATE_SEALING)) {
+            throw new IllegalStateException("Attempted to seal an already-sealed Data Tree.");
+        }
 
         var current = AbstractReadyIterator.create(rootNode, getStrategy());
         do {
             current = current.process(version);
         } while (current != null);
+
+        // Make sure all affects are visible before returning, as this object may be handed off to another thread, which
+        // needs to see any HashMap.modCount mutations completed. This is needed because isSealed() is now performing
+        // only the equivalent of an acquireFence()
+        STATE.setRelease(this, STATE_SEALED);
     }
 }