package com.atlassian.stash.internal.concurrent;

import com.atlassian.bitbucket.concurrent.BucketedExecutorSettings;
import com.hazelcast.core.HazelcastInstance;

import javax.annotation.Nonnull;
import java.io.Serializable;

/**
 * @since 3.3
 */
public class HazelcastBucketedExecutorFactory implements BucketedExecutorFactory {

    private final ClassLoader classLoader;
    private final HazelcastInstance hazelcast;
    private final ThreadGroup threadGroup;

    public HazelcastBucketedExecutorFactory(ClassLoader classLoader, HazelcastInstance hazelcast,
                                            ThreadGroup threadGroup) {
        this.classLoader = classLoader;
        this.hazelcast = hazelcast;
        this.threadGroup = threadGroup;
    }

    @Nonnull
    @Override
    public <T extends Serializable> InternalBucketedExecutor<T> create(@Nonnull String name, @Nonnull BucketedExecutorSettings<T> settings) {
        ConfigurableThreadFactory threadFactory = new ConfigurableThreadFactory();
        threadFactory.setClassLoader(classLoader);
        threadFactory.setDaemon(true);
        threadFactory.setThreadGroup(threadGroup);
        threadFactory.setThreadNamePrefix(name);

        return new HazelcastBucketedExecutor<>(name, settings, hazelcast, threadFactory);
    }
}
