001/*
002 * The contents of this file are subject to the terms of the Common Development and
003 * Distribution License (the License). You may not use this file except in compliance with the
004 * License.
005 *
006 * You can obtain a copy of the License at legal/CDDLv1.0.txt. See the License for the
007 * specific language governing permission and limitations under the License.
008 *
009 * When distributing Covered Software, include this CDDL Header Notice in each file and include
010 * the License file at legal/CDDLv1.0.txt. If applicable, add the following below the CDDL
011 * Header, with the fields enclosed by brackets [] replaced by your own identifying
012 * information: "Portions Copyright [year] [name of copyright owner]".
013 *
014 * Copyright 2014-2016 ForgeRock AS.
015 */
016package org.opends.server.replication.service;
017
018import java.util.concurrent.ConcurrentSkipListSet;
019import java.util.concurrent.atomic.AtomicLong;
020
021import org.forgerock.opendj.ldap.DN;
022
023/**
024 * Class useful for the case where DS/RS instances are collocated inside the
025 * same JVM. It synchronizes the shutdown of the DS and RS sides.
026 * <p>
027 * More specifically, it ensures a ReplicaOfflineMsg sent by the DS is
028 * relayed/forwarded by the collocated RS to the other RSs in the topology
029 * before the whole process shuts down.
030 *
031 * @since OPENDJ-1453
032 */
033public class DSRSShutdownSync
034{
035  private static final ConcurrentSkipListSet<DN> replicaOfflineMsgs = new ConcurrentSkipListSet<>();
036  private static AtomicLong stopInstanceTimestamp = new AtomicLong();
037
038  /**
039   * Message has been sent.
040   *
041   * @param baseDN
042   *          the domain for which the message has been sent
043   */
044  public void replicaOfflineMsgSent(DN baseDN)
045  {
046    stopInstanceTimestamp.compareAndSet(0, System.currentTimeMillis());
047    replicaOfflineMsgs.add(baseDN);
048  }
049
050  /**
051   * Message has been forwarded.
052   *
053   * @param baseDN
054   *          the domain for which the message has been sent
055   */
056  public void replicaOfflineMsgForwarded(DN baseDN)
057  {
058    replicaOfflineMsgs.remove(baseDN);
059  }
060
061  /**
062   * Whether a ReplicationServer ServerReader or ServerWriter can proceed with
063   * shutdown.
064   *
065   * @param baseDN
066   *          the baseDN of the ServerReader or ServerWriter .
067   * @return true if the caller can shutdown, false otherwise
068   */
069  public boolean canShutdown(DN baseDN)
070  {
071    return !replicaOfflineMsgs.contains(baseDN)
072        || System.currentTimeMillis() - stopInstanceTimestamp.get() > 5000;
073  }
074}