dorkbox.messageBus.subscription.Subscription Maven / Gradle / Ivy
/*
* Copyright 2016 dorkbox, llc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dorkbox.messageBus.subscription;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
import com.esotericsoftware.kryo.util.IdentityMap;
import dorkbox.messageBus.common.MessageHandler;
import dorkbox.messageBus.error.ErrorHandler;
/**
* A subscription is a container that manages exactly one message handler of all registered
* message listeners of the same class, i.e. all subscribed instances (excluding subclasses) of a message
* will be referenced in the subscription created for a message.
*
* There will be as many unique subscription objects per message listener class as there are message handlers
* defined in the message listeners class hierarchy.
*
* This class uses the "single writer principle", so that the subscription are only MODIFIED by a single thread,
* but are READ by X number of threads (in a safe way). This uses object thread visibility/publication to work.
*
* @author dorkbox, llc
* Date: 2/3/16
*/
public abstract
class Subscription {
private static final AtomicInteger ID_COUNTER = new AtomicInteger();
private final int ID = ID_COUNTER.getAndIncrement();
// this is the listener class that created this subscription
private final Class> listenerClass;
// the handler's metadata -> for each handler in a listener, a unique subscription context is created
private final MessageHandler handler;
// This is only touched by a single thread!
private final IdentityMap