/*
 * Copyright 2019, TeamDev. All rights reserved.
 *
 * Redistribution and use in source and/or binary forms, with or without
 * modification, must retain the above copyright notice and the following
 * disclaimer.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

package io.spine.client;

import com.google.common.annotations.VisibleForTesting;

import java.util.ArrayList;
import java.util.List;

import static com.google.common.base.Preconditions.checkNotNull;

/**
 * Maintains the list of subscriptions created by the {@link Client} which are
 * not cancelled yet. Cancels remaining subscriptions upon request.
 */
final class ActiveSubscriptions {

    private final List<Subscription> subscriptions = new ArrayList<>();

    synchronized void remember(Subscription s) {
        subscriptions.add(checkNotNull(s));
    }

    synchronized void forget(Subscription s) {
        subscriptions.remove(checkNotNull(s));
    }

    synchronized void cancelAll(Client client) {
        subscriptions.forEach(client::cancel);
    }

    @VisibleForTesting
    synchronized boolean contains(Subscription s) {
        return subscriptions.contains(s);
    }
}

@@ -1470,16 +1470,77 @@
 t%3C%3E();%0A%0A
+    /** Remembers the passed subscription for future use. */%0A
     sync
@@ -1623,32 +1623,76 @@
 ull(s));%0A    %7D%0A%0A
+    /** Forgets the passed subscription. */%0A
     synchronized
@@ -1772,24 +1772,76 @@
 s));%0A    %7D%0A%0A
+    /** Cancels all the remembered subscription. */%0A
     synchron
@@ -1889,46 +1889,299 @@
     
-subscriptions.forEach(
+// Use the loop approach to avoid concurrent modification because the %60Client%60 modifies%0A        // active subscriptions when canceling.%0A        while (!subscriptions.isEmpty()) %7B%0A            Subscription subscription = subscriptions.get(0);%0A            
 client
-::
+.
 cancel
-);
+(subscription);%0A        %7D
 %0A   
@@ -2306,11 +2306,118 @@
 );%0A    %7D
+%0A%0A    @VisibleForTesting%0A    synchronized boolean isEmpty() %7B%0A        return subscriptions.isEmpty();%0A    %7D
 %0A%7D%0A

Fix concurrent modification