BUG-1886: implement lock-free InMemoryDataTree.commit()
[yangtools.git] / yang / yang-data-impl / src / main / java / org / opendaylight / yangtools / yang / data / impl / schema / tree / DataTreeState.java
1 /*
2  * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.yangtools.yang.data.impl.schema.tree;
9
10 import com.google.common.base.Preconditions;
11 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.TreeNode;
12 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
13
14 /**
15  * Instances of this class hold the current state of a DataTree instance.
16  * The need for encapsulation stems from atomic updates, which potentially change
17  * multiple fields in one go.
18  */
19 final class DataTreeState {
20     private final LatestOperationHolder holder;
21     private final SchemaContext schemaContext;
22     private final TreeNode root;
23
24     private DataTreeState(final TreeNode root) {
25         this.root = Preconditions.checkNotNull(root);
26         holder = new LatestOperationHolder();
27         schemaContext = null;
28     }
29
30     private DataTreeState(final TreeNode root, final LatestOperationHolder holder, final SchemaContext schemaContext) {
31         // It should be impossible to instantiate a new root without a SchemaContext
32         this.schemaContext = Preconditions.checkNotNull(schemaContext);
33         this.holder = Preconditions.checkNotNull(holder);
34         this.root = Preconditions.checkNotNull(root);
35     }
36
37     static DataTreeState createInitial(final TreeNode root) {
38         return new DataTreeState(root);
39     }
40
41     TreeNode getRoot() {
42         return root;
43     }
44
45     InMemoryDataTreeSnapshot newSnapshot() {
46         return new InMemoryDataTreeSnapshot(schemaContext, root, holder.newSnapshot());
47     }
48
49     DataTreeState withSchemaContext(final SchemaContext newSchemaContext, final SchemaAwareApplyOperation operation) {
50         holder.setCurrent(operation);
51         return new DataTreeState(root, holder, newSchemaContext);
52     }
53
54     DataTreeState withRoot(final TreeNode newRoot) {
55         return new DataTreeState(newRoot, holder, schemaContext);
56     }
57 }