BUG-2882: implement DataTreeModificationCursor
[yangtools.git] / yang / yang-data-impl / src / main / java / org / opendaylight / yangtools / yang / data / impl / schema / tree / AbstractCursorAware.java
1 /*
2  * Copyright (c) 2015 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 java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
12 import org.slf4j.Logger;
13 import org.slf4j.LoggerFactory;
14
15 abstract class AbstractCursorAware {
16     private static final Logger LOG = LoggerFactory.getLogger(AbstractCursorAware.class);
17     @SuppressWarnings("rawtypes")
18     private static final AtomicReferenceFieldUpdater<AbstractCursorAware, AbstractCursor> CURSOR_UPDATER =
19             AtomicReferenceFieldUpdater.newUpdater(AbstractCursorAware.class, AbstractCursor.class, "cursor");
20     private volatile AbstractCursor<?> cursor = null;
21
22     protected <T extends AbstractCursor<?>> T openCursor(final T cursor) {
23         final boolean success = CURSOR_UPDATER.compareAndSet(this, null, cursor);
24         Preconditions.checkState(success, "Modification %s has cursor attached at path %s", this, this.cursor.getRootPath());
25         return cursor;
26     }
27
28     final void closeCursor(final AbstractCursor<?> cursor) {
29         final boolean success = CURSOR_UPDATER.compareAndSet(this, cursor, null);
30         if (!success) {
31             LOG.warn("Attempted to close cursor %s while %s is open", cursor, this.cursor);
32         }
33     }
34 }