Split out yang-data-tree-{api,spi}
[yangtools.git] / data / yang-data-tree-ri / src / main / java / org / opendaylight / yangtools / yang / data / tree / impl / 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.tree.impl;
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 cursorToOpen) {
23         final boolean success = CURSOR_UPDATER.compareAndSet(this, null, cursorToOpen);
24         Preconditions.checkState(success, "Modification %s has cursor attached at path %s", this,
25             this.cursor.getRootPath());
26         return cursorToOpen;
27     }
28
29     final void closeCursor(final AbstractCursor<?> cursorToClose) {
30         final boolean success = CURSOR_UPDATER.compareAndSet(this, cursorToClose, null);
31         if (!success) {
32             LOG.warn("Attempted to close cursor {} while {} is open", cursorToClose, this.cursor);
33         }
34     }
35 }