Merge "Mark ModifiedNode as NotThreadSafe"
[yangtools.git] / common / concepts / src / main / java / org / opendaylight / yangtools / concepts / AbstractRegistration.java
1 /*
2  * Copyright (c) 2013 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.concepts;
9
10 import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
11
12 /**
13  * Utility registration handle. It is a convenience for register-style method
14  * which can return an AutoCloseable realized by a subclass of this class.
15  * Invoking the close() method triggers unregistration of the state the method
16  * installed.
17  */
18 public abstract class AbstractRegistration implements AutoCloseable {
19     private static final AtomicIntegerFieldUpdater<AbstractRegistration> CLOSED_UPDATER =
20             AtomicIntegerFieldUpdater.newUpdater(AbstractRegistration.class, "closed");
21     private volatile int closed = 0;
22
23     /**
24      * Remove the state referenced by this registration. This method is
25      * guaranteed to be called at most once. The referenced state must be
26      * retained until this method is invoked.
27      */
28     protected abstract void removeRegistration();
29
30     /**
31      * Query the state of this registration. Returns true if it was
32      * closed.
33      *
34      * @return true if the registration was closed, false otherwise.
35      */
36     protected final boolean isClosed() {
37         return closed != 0;
38     }
39
40     @Override
41     public final void close() {
42         if (CLOSED_UPDATER.compareAndSet(this, 0, 1)) {
43             removeRegistration();
44         }
45     }
46 }