All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.smallrye.faulttolerance.core.InvocationContext Maven / Gradle / Ivy

package io.smallrye.faulttolerance.core;

import java.util.Collection;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ConcurrentMap;
import java.util.function.Consumer;

public final class InvocationContext implements Callable {
    private final Callable delegate;

    public InvocationContext(Callable delegate) {
        this.delegate = delegate;
    }

    @Override
    public V call() throws Exception {
        return delegate.call();
    }

    // arbitrary contextual data

    private final ConcurrentMap, Object> data = new ConcurrentHashMap<>(4);

    public  void set(Class clazz, T object) {
        data.put(clazz, object);
    }

    public  void remove(Class clazz) {
        data.remove(clazz);
    }

    public  T get(Class clazz) {
        return clazz.cast(data.get(clazz));
    }

    public  T get(Class clazz, T defaultValue) {
        T value = get(clazz);
        return value != null ? value : defaultValue;
    }

    // out-of-band communication between fault tolerance strategies in a single chain

    private final ConcurrentMap, Collection>> eventHandlers = new ConcurrentHashMap<>();

    public  void registerEventHandler(Class eventType, Consumer handler) {
        eventHandlers.computeIfAbsent(eventType, ignored -> new ConcurrentLinkedQueue<>()).add(handler);
    }

    public  void fireEvent(E event) {
        Collection> handlers = eventHandlers.get(event.getClass());
        if (handlers != null) {
            for (Consumer handler : handlers) {
                @SuppressWarnings("unchecked")
                Consumer consumer = (Consumer) handler;
                consumer.accept(event);
            }
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy