Arcturus-Community/src/main/java/com/eu/habbo/threading/ThreadPooling.java

78 lines
2.0 KiB
Java
Raw Normal View History

2018-07-06 15:30:00 +02:00
package com.eu.habbo.threading;
import com.eu.habbo.Emulator;
import io.netty.util.concurrent.DefaultThreadFactory;
2020-05-03 01:46:07 +02:00
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
2018-07-06 15:30:00 +02:00
2018-09-28 21:25:00 +02:00
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
2018-07-06 15:30:00 +02:00
2019-05-26 20:14:53 +02:00
public class ThreadPooling {
2020-05-03 01:46:07 +02:00
private static final Logger LOGGER = LoggerFactory.getLogger(ThreadPooling.class);
2018-07-06 15:30:00 +02:00
public final int threads;
private final ScheduledExecutorService scheduledPool;
private volatile boolean canAdd;
2019-05-26 20:14:53 +02:00
public ThreadPooling(Integer threads) {
2018-07-06 15:30:00 +02:00
this.threads = threads;
2020-05-04 22:24:09 +02:00
this.scheduledPool = new HabboExecutorService(this.threads, new DefaultThreadFactory("HabExec"));
2018-07-06 15:30:00 +02:00
this.canAdd = true;
2020-05-03 01:46:07 +02:00
LOGGER.info("Thread Pool -> Loaded!");
2018-07-06 15:30:00 +02:00
}
2019-05-26 20:14:53 +02:00
public ScheduledFuture run(Runnable run) {
try {
if (this.canAdd) {
2018-07-06 15:30:00 +02:00
return this.run(run, 0);
2019-05-26 20:14:53 +02:00
} else {
if (Emulator.isShuttingDown) {
2019-04-22 01:42:00 +02:00
run.run();
}
}
2019-05-26 20:14:53 +02:00
} catch (Exception e) {
2020-05-03 01:46:07 +02:00
LOGGER.error("Caught exception", e);
2018-07-06 15:30:00 +02:00
}
return null;
}
2019-05-26 20:14:53 +02:00
public ScheduledFuture run(Runnable run, long delay) {
try {
if (this.canAdd) {
2020-04-23 19:08:37 +02:00
return this.scheduledPool.schedule(() -> {
try {
run.run();
} catch (Exception e) {
2020-05-03 01:46:07 +02:00
LOGGER.error("Caught exception", e);
2018-07-06 15:30:00 +02:00
}
}, delay, TimeUnit.MILLISECONDS);
}
2019-05-26 20:14:53 +02:00
} catch (Exception e) {
2020-05-03 01:46:07 +02:00
LOGGER.error("Caught exception", e);
2018-07-06 15:30:00 +02:00
}
return null;
}
2019-05-26 20:14:53 +02:00
public void shutDown() {
2018-07-06 15:30:00 +02:00
this.canAdd = false;
this.scheduledPool.shutdownNow();
2020-05-03 01:46:07 +02:00
LOGGER.info("Threading -> Disposed!");
2018-07-06 15:30:00 +02:00
}
2019-05-26 20:14:53 +02:00
public void setCanAdd(boolean canAdd) {
2019-04-22 01:42:00 +02:00
this.canAdd = canAdd;
}
2019-05-26 20:14:53 +02:00
public ScheduledExecutorService getService() {
2018-07-06 15:30:00 +02:00
return this.scheduledPool;
}
}