001/*
002 * (C) Copyright 2006-2020 Nuxeo (http://nuxeo.com/) and others.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 *
016 * Contributors:
017 *     Florent Guillaume
018 */
019package org.nuxeo.ecm.core.storage;
020
021import org.nuxeo.runtime.pubsub.SerializableAccumulableInvalidations;
022
023/**
024 * Queue of invalidations.
025 * <p>
026 * All invalidations added are accumulated (from multiple threads), then returned when asked for.
027 *
028 * @param <T> the invalidations type
029 * @since 11.1
030 */
031public abstract class InvalidationsQueue<T extends SerializableAccumulableInvalidations> {
032
033    public T queue; // used under synchronization
034
035    /** used for debugging */
036    public final String name;
037
038    public InvalidationsQueue(String name) {
039        queue = newInvalidations();
040        this.name = name;
041    }
042
043    /** Constructs new empty invalidations, of type {@link T}. */
044    public abstract T newInvalidations();
045
046    /**
047     * Adds invalidations.
048     * <p>
049     * May be called asynchronously from multiple threads.
050     */
051    public synchronized void addInvalidations(T invalidations) {
052        queue.add(invalidations);
053    }
054
055    /**
056     * Gets the queued invalidations and resets the queue.
057     */
058    public synchronized T getInvalidations() {
059        T invalidations = queue;
060        queue = newInvalidations();
061        return invalidations;
062    }
063
064    @Override
065    public String toString() {
066        return getClass().getSimpleName() + '(' + name + ')';
067    }
068
069}