7ffd08fd7588698d0ea095da9570e01707dce3c8
[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 java.lang.invoke.MethodHandles;
11 import java.lang.invoke.VarHandle;
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     private static final VarHandle CURSOR;
18
19     static {
20         try {
21             CURSOR = MethodHandles.lookup().findVarHandle(AbstractCursorAware.class, "cursor", AbstractCursor.class);
22         } catch (NoSuchFieldException | IllegalAccessException e) {
23             throw new ExceptionInInitializerError(e);
24         }
25     }
26
27     @SuppressWarnings("unused")
28     private volatile AbstractCursor<?> cursor;
29
30     protected <T extends AbstractCursor<?>> T openCursor(final T cursorToOpen) {
31         final var witness = (AbstractCursor<?>) CURSOR.compareAndExchange(this, null, cursorToOpen);
32         if (witness != null) {
33             throw new IllegalStateException(
34                 "Modification " + this + " has cursor attached at path " + witness.getRootPath());
35         }
36         return cursorToOpen;
37     }
38
39     final void closeCursor(final AbstractCursor<?> cursorToClose) {
40         final var witness = (AbstractCursor<?>) CURSOR.compareAndExchange(this, cursorToClose, null);
41         if (witness != cursorToClose) {
42             LOG.warn("Attempted to close cursor {} while {} is open", cursorToClose, witness);
43         }
44     }
45 }