2 * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.yangtools.concepts;
10 import com.google.common.base.MoreObjects;
11 import com.google.common.base.MoreObjects.ToStringHelper;
12 import java.lang.invoke.MethodHandles;
13 import java.lang.invoke.VarHandle;
16 * Utility registration handle. It is a convenience for register-style method which can return an AutoCloseable realized
17 * by a subclass of this class. Invoking the close() method triggers unregistration of the state the method installed.
19 public abstract class AbstractRegistration implements Registration {
20 private static final VarHandle CLOSED;
22 // All access needs to go through this handle
23 @SuppressWarnings("unused")
24 private volatile byte closed;
28 CLOSED = MethodHandles.lookup().findVarHandle(AbstractRegistration.class, "closed", byte.class);
29 } catch (ReflectiveOperationException e) {
30 throw new ExceptionInInitializerError(e);
35 * Remove the state referenced by this registration. This method is guaranteed to be called at most once.
36 * Referenced state must be retained until this method is invoked.
38 protected abstract void removeRegistration();
41 * Query the state of this registration. Returns true if it was closed.
43 * @return true if the registration was closed, false otherwise.
45 public final boolean isClosed() {
46 return (byte) CLOSED.getAcquire(this) != 0;
50 public final void close() {
51 // We want full setVolatile() memory semantics here, as all state before calling this method
52 // needs to be visible
53 if (CLOSED.compareAndSet(this, (byte) 0, (byte) 1)) {
59 public final String toString() {
60 return addToStringAttributes(MoreObjects.toStringHelper(this).omitNullValues()).toString();
63 protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
64 return toStringHelper.add("closed", isClosed());