Как использовать собственный ThreadPoolExecutor в статье?JAVA

Программисты JAVA общаются здесь
Ответить Пред. темаСлед. тема
Anonymous
 Как использовать собственный ThreadPoolExecutor в статье?

Сообщение Anonymous »

Недавно я начал использовать Vert.x. Раньше я использовал фреймворк Play. В игре я использовал систему Actor с пользовательским MessageDispatcherConfigurator, чтобы использовать собственный ThreadPoolExecutor, который распространяет контекст потока при переключении исполнителей или переключении потоков в одном и том же пуле исполнителей.
CustomDispatcherConfigurator
public class CustomDispatcherConfigurator extends MessageDispatcherConfigurator {

private final CustomDispatcher instance;

public CustomDispatcherConfigurator(Config config, DispatcherPrerequisites prerequisites) {
super(config, prerequisites);
Config threadPoolConfig = config.getConfig("thread-pool-executor");
int fixedPoolSize = threadPoolConfig.getInt("fixed-pool-size");
instance = new CustomDispatcher(
this,
config.getString("id"),
config.getInt("throughput"),
Duration.create(config.getDuration("throughput-deadline-time", TimeUnit.NANOSECONDS), TimeUnit.NANOSECONDS),
(id, threadFactory) -> () -> new CustomThreadPoolExecutor(fixedPoolSize,
fixedPoolSize,
threadPoolConfig.getDuration("keep-alive-time", TimeUnit.MILLISECONDS),
TimeUnit.MILLISECONDS,
new LinkedBlockingDeque(),
new ThreadFactory() {
private int threadId = 1;

@Override
public Thread newThread(@NotNull Runnable r) {
Thread thread = new Thread(r);
thread.setName(config.getString("name") + "-" + threadId++);
return thread;
}
}),
Duration.create(config.getDuration("shutdown-timeout", TimeUnit.MILLISECONDS), TimeUnit.MILLISECONDS)
);
}

@Override
public MessageDispatcher dispatcher() {
return instance;
}

}

class CustomDispatcher extends Dispatcher {

public CustomDispatcher(MessageDispatcherConfigurator _configurator,
String id,
int throughput,
Duration throughputDeadlineTime,
ExecutorServiceFactoryProvider executorServiceFactoryProvider,
scala.concurrent.duration.FiniteDuration shutdownTimeout) {
super(_configurator, id, throughput, throughputDeadlineTime, executorServiceFactoryProvider, shutdownTimeout);
}

}

CustomThreadPoolExecutor
public class CustomThreadPoolExecutor extends ThreadPoolExecutor {

public CustomThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
@NotNull TimeUnit unit,
@NotNull BlockingQueue workQueue) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
}

public CustomThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
@NotNull TimeUnit unit,
@NotNull BlockingQueue workQueue,
@NotNull ThreadFactory threadFactory) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory);
}

public CustomThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
@NotNull TimeUnit unit,
@NotNull BlockingQueue workQueue,
@NotNull RejectedExecutionHandler handler) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, handler);
}

public CustomThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
@NotNull TimeUnit unit,
@NotNull BlockingQueue workQueue,
@NotNull ThreadFactory threadFactory,
@NotNull RejectedExecutionHandler handler) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler);
}

@Override
public @NotNull Future submit(@NotNull Callable task) {
return super.submit(ContextUtility.wrapWithContext(task));
}

@Override
public @NotNull Future submit(@NotNull Runnable task, T result) {
return super.submit(ContextUtility.wrapWithContext(task), result);
}

@Override
public @NotNull Future submit(@NotNull Runnable task) {
return super.submit(ContextUtility.wrapWithContext(task));
}

@Override
public void execute(@NotNull Runnable task) {
super.execute(ContextUtility.wrapWithContext(task));
}
}

Я хочу использовать один и тот же класс CustomThreadPoolExecutor вместо ThreadPoolExecutor по умолчанию во всех моих Verticles. Как мне это сделать? Я изучил SPI ExecutorServiceFactory и реализовал его, используя свой CustomThreadPoolExecutor в его методе createExecutor, но я не знаю, как использовать этот CustomExecutorServiceFactory при развертывании моих вершин.
CustomExecutorServiceFactory
public class CustomExecutorServiceFactory implements ExecutorServiceFactory {
@Override
public void init(VertxBuilder builder) {
ExecutorServiceFactory.super.init(builder);
}

@Override
public ExecutorService createExecutor(ThreadFactory threadFactory, Integer concurrency, Integer maxConcurrency) {
return new CustomThreadPoolExecutor(concurrency, maxConcurrency, 10L, TimeUnit.MICROSECONDS,
new LinkedBlockingQueue(), threadFactory);
}
}


Подробнее здесь: https://stackoverflow.com/questions/786 ... a-verticle
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение
  • Как использовать собственный ThreadPoolExecutor в статье?
    Anonymous » » в форуме JAVA
    0 Ответы
    12 Просмотры
    Последнее сообщение Anonymous
  • Согласно статье «auto(x)» (wg21.link/p0849), почему «return std::forward<T>» не может идеально переслать параметры, введ
    Гость » » в форуме C++
    0 Ответы
    29 Просмотры
    Последнее сообщение Гость
  • Приложение отклонено по статье 17.2. Запрос идентификатора электронной почты
    Anonymous » » в форуме IOS
    0 Ответы
    12 Просмотры
    Последнее сообщение Anonymous
  • Как узнать количество столбцов в статье?
    Anonymous » » в форуме Jquery
    0 Ответы
    15 Просмотры
    Последнее сообщение Anonymous
  • Как получить доступ к загруженному видео/статье из Google Adk Web с помощью инструмента ADK
    Anonymous » » в форуме Python
    0 Ответы
    2 Просмотры
    Последнее сообщение Anonymous

Вернуться в «JAVA»