ThreadPool manager rework.

This commit is contained in:
MobiusDev
2017-08-23 05:23:31 +00:00
parent 374c53df4b
commit b77de360af
718 changed files with 3180 additions and 7193 deletions
+16 -20
View File
@@ -132,33 +132,29 @@ SkillCheckGM = False
# Thread Configuration
# ---------------------------------------------------------------------------
# Extreme caution should be here, set to defaults if you do not know what you are doing.
# These could possibly hurt your servers performance or improve it depending on your server's configuration, size, and other factors.
# Default: 10
ThreadPoolSizeEffects = 50
# Determines the amount of scheduled thread pools. If set to -1, the server will decide the amount depending on the available processors.
Default: -1
ScheduledThreadPoolCount = -1
# Default: 13
ThreadPoolSizeGeneral = 65
# Specifies how many threads will be in a single scheduled pool.
Default: 4
ThreadsPerScheduledThreadPool = 40
# Default: 2
ThreadPoolSizeEvents = 10
# Determines the amount of instant thread pools. If set to -1, the server will decide the amount depending on the available processors.
Default: -1
InstantThreadPoolCount = -1
# Specifies how many threads will be in a single instant pool.
Default: 2
ThreadsPerInstantThreadPool = 20
# Default: 2
UrgentPacketThreadCoreSize = 20
# Default: 4
GeneralPacketThreadCoreSize = 20
# Default: 4
GeneralThreadCoreSize = 20
# Default: 6
AiMaxThread = 30
# Default: 5
EventsMaxThread = 25
# Dead Lock Detector (a separate thread for detecting deadlocks).
# ---------------------------------------------------------------------------
# Dead Lock Detector (separate thread for detecting deadlocks)
# ---------------------------------------------------------------------------
# For improved crash logs and automatic restart in deadlock case if enabled.
# Check interval is in seconds.
# Default: True
@@ -8,7 +8,6 @@
</tr>
</table>
<br>
<br>
<font color="LEVEL">General:<font><br1>
<table width="270" border="0" bgcolor="444444">
<tr>
@@ -76,30 +75,5 @@
<td><font color="00FF00">%totalMem% MB</font></td>
</tr>
</table>
<br>
<font color="LEVEL">Thread - General (STP):<font><br1>
%theardInfoGen%
<br>
<font color="LEVEL">Thread - Effects (STP):<font><br1>
%theardInfoEff%
<br>
<font color="LEVEL">Thread - AI (STP):<font><br1>
%theardInfoAi%
<br>
<font color="LEVEL">Thread - Event (STP):<font><br1>
%theardInfoEvent%
<br>
<font color="LEVEL">Thread - Packets (TP):<font><br1>
%theardInfoPack%
<br>
<font color="LEVEL">Thread - I/O Packets (TP):<font><br1>
%theardInfoIOPack%
<br>
<font color="LEVEL">Thread - General Tasks (TP):<font><br1>
%theardInfoGenTask%
<br>
<font color="LEVEL">Thread - Event Tasks (TP):<font><br1>
%theardInfoEvnTask%
<br>
</center>
</body></html>
@@ -258,7 +258,7 @@ public final class QueenAnt extends AbstractNpcAI
{
((L2MonsterInstance) npc).getMinionList().spawnMinions(npc.getParameters().getMinionList("Privates"));
}
_task = ThreadPoolManager.getInstance().scheduleAiAtFixedRate(new QueenAntTask(), 5 * 1000, 5 * 1000);
_task = ThreadPoolManager.scheduleAtFixedRate(new QueenAntTask(), 5 * 1000, 5 * 1000);
break;
}
}
@@ -112,7 +112,7 @@ public final class Elpies extends Event
Broadcast.toAllOnlinePlayers("Help us exterminate them!");
Broadcast.toAllOnlinePlayers("You have " + EVENT_DURATION_MINUTES + " minutes!");
_eventTask = ThreadPoolManager.getInstance().scheduleGeneral(() ->
_eventTask = ThreadPoolManager.schedule(() ->
{
Broadcast.toAllOnlinePlayers("Time is up!");
eventStop();
@@ -138,7 +138,7 @@ public final class Race extends Event
Broadcast.toAllOnlinePlayers("Visit Event Manager in Dion village and signup, you have " + _time_register + " min before Race Start...");
// Schedule Event end
_eventTask = ThreadPoolManager.getInstance().scheduleGeneral(() -> StartRace(), _time_register * 60 * 1000);
_eventTask = ThreadPoolManager.schedule(() -> StartRace(), _time_register * 60 * 1000);
return true;
@@ -181,7 +181,7 @@ public final class Race extends Event
}
}
// Schedule timeup for Race
_eventTask = ThreadPoolManager.getInstance().scheduleGeneral(() -> timeUp(), _time_race * 60 * 1000);
_eventTask = ThreadPoolManager.schedule(() -> timeUp(), _time_race * 60 * 1000);
}
@Override
@@ -309,7 +309,6 @@ import handlers.telnethandlers.server.ServerAbort;
import handlers.telnethandlers.server.ServerRestart;
import handlers.telnethandlers.server.ServerShutdown;
import handlers.telnethandlers.server.Status;
import handlers.telnethandlers.server.ThreadPoolDebug;
import handlers.usercommandhandlers.ChannelDelete;
import handlers.usercommandhandlers.ChannelInfo;
import handlers.usercommandhandlers.ChannelLeave;
@@ -751,7 +750,6 @@ public class MasterHandler
TelnetServer.getInstance().addHandler(new ServerRestart());
TelnetServer.getInstance().addHandler(new ServerShutdown());
TelnetServer.getInstance().addHandler(new Status());
TelnetServer.getInstance().addHandler(new ThreadPoolDebug());
TelnetServer.getInstance().addHandler(new handlers.telnethandlers.server.Debug());
}
@@ -20,14 +20,12 @@ import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import com.l2jmobius.Config;
import com.l2jmobius.gameserver.GameServer;
import com.l2jmobius.gameserver.GameTimeController;
import com.l2jmobius.gameserver.ThreadPoolManager;
import com.l2jmobius.gameserver.cache.HtmCache;
import com.l2jmobius.gameserver.data.xml.impl.AdminData;
import com.l2jmobius.gameserver.handler.IAdminCommandHandler;
@@ -72,14 +70,6 @@ public class AdminServerInfo implements IAdminCommandHandler
html.replace("%usedMem%", (RunTime.maxMemory() / mb) - (((RunTime.maxMemory() - RunTime.totalMemory()) + RunTime.freeMemory()) / mb));
html.replace("%freeMem%", ((RunTime.maxMemory() - RunTime.totalMemory()) + RunTime.freeMemory()) / mb);
html.replace("%totalMem%", Runtime.getRuntime().maxMemory() / 1048576);
html.replace("%theardInfoGen%", buildTheardInfo("GENERAL"));
html.replace("%theardInfoEff%", buildTheardInfo("EFFECTS"));
html.replace("%theardInfoAi%", buildTheardInfo("AI"));
html.replace("%theardInfoEvent%", buildTheardInfo("EVENT"));
html.replace("%theardInfoPack%", buildTheardInfo("PACKETS"));
html.replace("%theardInfoIOPack%", buildTheardInfo("IOPACKETS"));
html.replace("%theardInfoGenTask%", buildTheardInfo("GENERAL_TASKS"));
html.replace("%theardInfoEvnTask%", buildTheardInfo("EVENT_TASKS"));
activeChar.sendPacket(html);
}
return true;
@@ -96,22 +86,6 @@ public class AdminServerInfo implements IAdminCommandHandler
return days + " Days, " + hours + " Hours, " + TimeUnit.MILLISECONDS.toMinutes(time) + " Minutes";
}
private String buildTheardInfo(String category)
{
final StringBuilder tb = new StringBuilder();
tb.append("<table width=\"270\" border=\"0\" bgcolor=\"444444\">");
for (Entry<String, Object> info : ThreadPoolManager.getInstance().getStats(category).getSet().entrySet())
{
tb.append("<tr>");
tb.append("<td>" + info.getKey() + ":</td>");
tb.append("<td><font color=\"00FF00\">" + info.getValue() + "</font></td>");
tb.append("</tr>");
}
tb.append("</table>");
return tb.toString();
}
private int getPlayersCount(String type)
{
switch (type)
@@ -46,7 +46,7 @@ public class AdminTest implements IAdminCommandHandler
{
if (command.equals("admin_stats"))
{
for (String line : ThreadPoolManager.getInstance().getStats())
for (String line : ThreadPoolManager.getStats())
{
activeChar.sendMessage(line);
}
@@ -57,7 +57,7 @@ public class ClassChange extends AbstractEffect
{
final L2PcInstance player = effected.getActingPlayer();
// TODO: FIX ME - Executing 1 second later otherwise interupted exception during storeCharBase()
ThreadPoolManager.getInstance().scheduleGeneral(() ->
ThreadPoolManager.schedule(() ->
{
final int activeClass = player.getClassId().getId();
@@ -67,7 +67,7 @@ public final class ServitorShare extends AbstractEffect
if (effected != null)
{
ThreadPoolManager.getInstance().scheduleEffect(new ScheduledEffectExitTask(effected, info.getSkill().getId()), 100);
ThreadPoolManager.schedule(new ScheduledEffectExitTask(effected, info.getSkill().getId()), 100);
}
}
}
@@ -162,7 +162,7 @@ public class JailHandler implements IPunishmentHandler
OlympiadManager.getInstance().removeDisconnectedCompetitor(player);
}
ThreadPoolManager.getInstance().scheduleGeneral(new TeleportTask(player, L2JailZone.getLocationIn()), 2000);
ThreadPoolManager.schedule(new TeleportTask(player, L2JailZone.getLocationIn()), 2000);
// Open a Html message to inform the player
final NpcHtmlMessage msg = new NpcHtmlMessage();
@@ -198,7 +198,7 @@ public class JailHandler implements IPunishmentHandler
*/
private static void removeFromPlayer(L2PcInstance player)
{
ThreadPoolManager.getInstance().scheduleGeneral(new TeleportTask(player, L2JailZone.getLocationOut()), 2000);
ThreadPoolManager.schedule(new TeleportTask(player, L2JailZone.getLocationOut()), 2000);
// Open a Html message to inform the player
final NpcHtmlMessage msg = new NpcHtmlMessage();
@@ -68,7 +68,7 @@ public class Debug implements ITelnetCommand
@Override
public String getUsage()
{
return "Debug <decay/packetsend/PacketTP/IOPacketTP/GeneralTP/full>";
return "Debug <decay/packetsend/full>";
}
@Override
@@ -108,90 +108,6 @@ public class Debug implements ITelnetCommand
player.sendPacket(sp);
return "Packet has been sent!";
}
case "PacketTP":
{
final String str = ThreadPoolManager.getInstance().getPacketStats();
int i = 0;
File f = new File("./log/StackTrace-PacketTP-" + i + ".txt");
while (f.exists())
{
i++;
f = new File("./log/StackTrace-PacketTP-" + i + ".txt");
}
f.getParentFile().mkdirs();
try
{
Files.write(f.toPath(), str.getBytes(StandardCharsets.UTF_8), StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE);
}
catch (IOException e)
{
LOGGER.log(Level.WARNING, "Couldn't write packet tp.", e);
}
return str;
}
case "IOPacketTP":
{
final String str = ThreadPoolManager.getInstance().getIOPacketStats();
int i = 0;
File f = new File("./log/StackTrace-IOPacketTP-" + i + ".txt");
while (f.exists())
{
i++;
f = new File("./log/StackTrace-IOPacketTP-" + i + ".txt");
}
f.getParentFile().mkdirs();
try
{
Files.write(f.toPath(), str.getBytes(StandardCharsets.UTF_8), StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE);
}
catch (IOException e)
{
LOGGER.log(Level.WARNING, "Couldn't write packet tp.", e);
}
return str;
}
case "GeneralTP":
{
final String str = ThreadPoolManager.getInstance().getGeneralStats();
int i = 0;
File f = new File("./log/StackTrace-GeneralTP-" + i + ".txt");
while (f.exists())
{
i++;
f = new File("./log/StackTrace-GeneralTP-" + i + ".txt");
}
f.getParentFile().mkdirs();
try
{
Files.write(f.toPath(), str.getBytes(StandardCharsets.UTF_8), StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE);
}
catch (IOException e)
{
LOGGER.log(Level.WARNING, "Couldn't write packet tp.", e);
}
return str;
}
case "GeneralScheduledTP":
{
final String str = ThreadPoolManager.getInstance().getGeneralStats();
int i = 0;
File f = new File("./log/StackTrace-GeneralScheduledTP-" + i + ".txt");
while (f.exists())
{
i++;
f = new File("./log/StackTrace-GeneralScheduledTP-" + i + ".txt");
}
f.getParentFile().mkdirs();
try
{
Files.write(f.toPath(), str.getBytes(StandardCharsets.UTF_8), StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE);
}
catch (IOException e)
{
LOGGER.log(Level.WARNING, "Couldn't write packet tp.", e);
}
return str;
}
case "full":
{
final Calendar cal = Calendar.getInstance();
@@ -283,7 +199,7 @@ public class Debug implements ITelnetCommand
}
sb.append("\r\n## Thread Pool Manager Statistics ##\r\n");
for (String line : ThreadPoolManager.getInstance().getStats())
for (String line : ThreadPoolManager.getStats())
{
sb.append(line);
sb.append("\r\n");
@@ -42,9 +42,9 @@ public class Performance implements ITelnetCommand
@Override
public String handle(ChannelHandlerContext ctx, String[] args)
{
ThreadPoolManager.getInstance().purge();
// ThreadPoolManager.purge();
final StringBuilder sb = new StringBuilder();
for (String line : ThreadPoolManager.getInstance().getStats())
for (String line : ThreadPoolManager.getStats())
{
sb.append(line + Config.EOL);
}
@@ -42,9 +42,9 @@ public class Purge implements ITelnetCommand
@Override
public String handle(ChannelHandlerContext ctx, String[] args)
{
ThreadPoolManager.getInstance().purge();
ThreadPoolManager.purge();
final StringBuilder sb = new StringBuilder("STATUS OF THREAD POOLS AFTER PURGE COMMAND:" + Config.EOL);
for (String line : ThreadPoolManager.getInstance().getStats())
for (String line : ThreadPoolManager.getStats())
{
sb.append(line + Config.EOL);
}
@@ -1,171 +0,0 @@
/*
* This file is part of the L2J Mobius project.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package handlers.telnethandlers.server;
import java.lang.reflect.Field;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.FutureTask;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.l2jmobius.Config;
import com.l2jmobius.gameserver.ThreadPoolManager;
import com.l2jmobius.gameserver.ThreadPoolManager.RunnableWrapper;
import com.l2jmobius.gameserver.network.telnet.ITelnetCommand;
import io.netty.channel.ChannelHandlerContext;
/**
* @author UnAfraid
*/
public class ThreadPoolDebug implements ITelnetCommand
{
private static final Logger LOGGER = Logger.getLogger(ThreadPoolDebug.class.getName());
@Override
public String getCommand()
{
return "threadpooldebug";
}
@Override
public String getUsage()
{
return "threadpooldebug [effect, general, ai, events]";
}
@Override
public String handle(ChannelHandlerContext ctx, String[] args)
{
String pool = "_generalScheduledThreadPool";
if (args.length > 0)
{
switch (args[0])
{
case "effect":
{
pool = "_effectsScheduledThreadPool";
break;
}
case "general":
{
pool = "_generalScheduledThreadPool";
break;
}
case "ai":
{
pool = "_aiScheduledThreadPool";
break;
}
case "events":
{
pool = "_eventScheduledThreadPool";
break;
}
default:
{
return args[0] + " is not implemented!";
}
}
}
final ScheduledThreadPoolExecutor executor = getObject(ThreadPoolManager.class, ThreadPoolManager.getInstance(), pool, ScheduledThreadPoolExecutor.class);
if (executor == null)
{
return "Couldn't retreive " + pool + "!";
}
Class<?> adapterClass;
try
{
adapterClass = Class.forName("java.util.concurrent.Executors$RunnableAdapter");
}
catch (Exception e)
{
return e.getMessage();
}
final Map<String, Integer> tasks = new HashMap<>();
for (Runnable run : executor.getQueue())
{
try
{
if (run instanceof FutureTask)
{
final Object callableObject = getObject(FutureTask.class, run, "callable", Object.class);
final Object taskObject = getObject(adapterClass, callableObject, "task", Object.class);
if (taskObject instanceof RunnableWrapper)
{
final Runnable task = getObject(RunnableWrapper.class, taskObject, "_r", Runnable.class);
final String name = task.getClass().getName();
final int times = tasks.containsKey(name) ? tasks.get(name) : 0;
tasks.put(name, times + 1);
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
final StringBuilder sb = new StringBuilder();
sb.append(pool + " queue size: " + executor.getQueue().size() + Config.EOL);
tasks.entrySet().stream().sorted(Comparator.comparingInt(Entry::getValue)).forEach(entry -> sb.append("Class: " + entry.getKey() + " = " + entry.getValue() + Config.EOL));
return sb.toString();
}
private static <T> T getObject(Class<?> sourceClass, Object sourceInstance, String fieldName, Class<T> targetClass)
{
try
{
final Field field = sourceClass.getDeclaredField(fieldName);
// Mark down if field was accessible
final boolean isAccessible = field.isAccessible();
// Enforce accessible to retrieve the object associated with this field
if (!isAccessible)
{
field.setAccessible(true);
}
// Get the object
final Object fieldObject = field.get(sourceInstance);
// Restore the original accessible state.
field.setAccessible(isAccessible);
// Make sure the object is the one we expect to be
if (targetClass.isInstance(fieldObject))
{
return targetClass.cast(fieldObject);
}
}
catch (Exception e)
{
LOGGER.log(Level.WARNING, "Error while retrieving object of " + sourceInstance.getClass().getName() + "." + fieldName, e);
}
return null;
}
}
@@ -428,14 +428,11 @@ public final class Config
public static boolean ALT_DEV_NO_SPAWNS;
public static boolean ALT_DEV_SHOW_QUESTS_LOAD_IN_LOGS;
public static boolean ALT_DEV_SHOW_SCRIPTS_LOAD_IN_LOGS;
public static int THREAD_P_EFFECTS;
public static int THREAD_P_GENERAL;
public static int THREAD_E_EVENTS;
public static int GENERAL_PACKET_THREAD_CORE_SIZE;
public static int SCHEDULED_THREAD_POOL_COUNT;
public static int THREADS_PER_SCHEDULED_THREAD_POOL;
public static int INSTANT_THREAD_POOL_COUNT;
public static int THREADS_PER_INSTANT_THREAD_POOL;
public static int IO_PACKET_THREAD_CORE_SIZE;
public static int GENERAL_THREAD_CORE_SIZE;
public static int AI_MAX_THREAD;
public static int EVENT_MAX_THREAD;
public static boolean DEADLOCK_DETECTOR;
public static int DEADLOCK_CHECK_INTERVAL;
public static boolean RESTART_ON_DEADLOCK;
@@ -1708,14 +1705,11 @@ public final class Config
ALT_DEV_NO_SPAWNS = General.getBoolean("AltDevNoSpawns", false) || Boolean.getBoolean("nospawns");
ALT_DEV_SHOW_QUESTS_LOAD_IN_LOGS = General.getBoolean("AltDevShowQuestsLoadInLogs", false);
ALT_DEV_SHOW_SCRIPTS_LOAD_IN_LOGS = General.getBoolean("AltDevShowScriptsLoadInLogs", false);
THREAD_P_EFFECTS = General.getInt("ThreadPoolSizeEffects", 10);
THREAD_P_GENERAL = General.getInt("ThreadPoolSizeGeneral", 13);
THREAD_E_EVENTS = General.getInt("ThreadPoolSizeEvents", 2);
SCHEDULED_THREAD_POOL_COUNT = General.getInt("ScheduledThreadPoolCount", -1);
THREADS_PER_SCHEDULED_THREAD_POOL = General.getInt("ThreadsPerScheduledThreadPool", 4);
INSTANT_THREAD_POOL_COUNT = General.getInt("InstantThreadPoolCount", -1);
THREADS_PER_INSTANT_THREAD_POOL = General.getInt("ThreadsPerInstantThreadPool", 2);
IO_PACKET_THREAD_CORE_SIZE = General.getInt("UrgentPacketThreadCoreSize", 2);
GENERAL_PACKET_THREAD_CORE_SIZE = General.getInt("GeneralPacketThreadCoreSize", 4);
GENERAL_THREAD_CORE_SIZE = General.getInt("GeneralThreadCoreSize", 4);
AI_MAX_THREAD = General.getInt("AiMaxThread", 6);
EVENT_MAX_THREAD = General.getInt("EventsMaxThread", 5);
DEADLOCK_DETECTOR = General.getBoolean("DeadLockDetector", true);
DEADLOCK_CHECK_INTERVAL = General.getInt("DeadLockCheckInterval", 20);
RESTART_ON_DEADLOCK = General.getBoolean("RestartOnDeadlock", false);
@@ -174,13 +174,15 @@ public class GameServer
{
final long serverLoadStart = System.currentTimeMillis();
printSection("IdFactory");
if (!IdFactory.getInstance().isInitialized())
{
LOGGER.severe(getClass().getSimpleName() + ": Could not read object IDs from database. Please check your configuration.");
throw new Exception("Could not initialize the ID factory");
}
ThreadPoolManager.getInstance();
printSection("ThreadPool");
ThreadPoolManager.init();
EventDispatcher.getInstance();
// load script engines
@@ -31,7 +31,7 @@ public final class ItemsAutoDestroy
protected ItemsAutoDestroy()
{
ThreadPoolManager.getInstance().scheduleGeneralAtFixedRate(this::removeItems, 5000, 5000);
ThreadPoolManager.scheduleAtFixedRate(this::removeItems, 5000, 5000);
}
public static ItemsAutoDestroy getInstance()
@@ -109,7 +109,7 @@ public class RecipeController
if (Config.ALT_GAME_CREATION)
{
_activeMakers.put(manufacturer.getObjectId(), maker);
ThreadPoolManager.getInstance().scheduleGeneral(maker, 100);
ThreadPoolManager.schedule(maker, 100);
}
else
{
@@ -158,7 +158,7 @@ public class RecipeController
if (Config.ALT_GAME_CREATION)
{
_activeMakers.put(player.getObjectId(), maker);
ThreadPoolManager.getInstance().scheduleGeneral(maker, 100);
ThreadPoolManager.schedule(maker, 100);
}
else
{
@@ -354,7 +354,7 @@ public class RecipeController
_player.broadcastPacket(msk);
_player.sendPacket(new SetupGauge(_player.getObjectId(), 0, _delay));
ThreadPoolManager.getInstance().scheduleGeneral(this, 100 + _delay);
ThreadPoolManager.schedule(this, 100 + _delay);
}
else
{
@@ -548,7 +548,7 @@ public class RecipeController
if (Config.ALT_GAME_CREATION && isWait)
{
_player.sendPacket(new SetupGauge(_player.getObjectId(), 0, _delay));
ThreadPoolManager.getInstance().scheduleGeneral(this, 100 + _delay);
ThreadPoolManager.schedule(this, 100 + _delay);
}
else
{
@@ -570,7 +570,7 @@ public class RecipeController
if (Config.ALT_GAME_CREATION && isWait)
{
_player.sendPacket(new SetupGauge(_player.getObjectId(), 0, _delay));
ThreadPoolManager.getInstance().scheduleGeneral(this, 100 + _delay);
ThreadPoolManager.schedule(this, 100 + _delay);
}
else
{
@@ -215,7 +215,7 @@ public class Shutdown extends Thread
// stop all thread pools
try
{
ThreadPoolManager.getInstance().shutdown();
ThreadPoolManager.shutdown();
LOGGER.info("Thread Pool Manager: Manager has been shut down(" + tc.getEstimatedTimeAndRestartCounter() + "ms).");
}
catch (Throwable t)
@@ -16,803 +16,284 @@
*/
package com.l2jmobius.gameserver;
import java.lang.Thread.UncaughtExceptionHandler;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.l2jmobius.Config;
import com.l2jmobius.gameserver.model.StatsSet;
/**
* This class handles thread pooling system. It relies on two ThreadPoolExecutor arrays, which poolers number is generated using config.
* <p>
* This class is made to handle all the ThreadPools used in L2J.
* Those arrays hold following pools :
* </p>
* <p>
* Scheduled Tasks can either be sent to a {@link #_generalScheduledThreadPool "general"} or {@link #_effectsScheduledThreadPool "effects"} {@link ScheduledThreadPoolExecutor ScheduledThreadPool}: The "effects" one is used for every effects (skills, hp/mp regen ...) while the "general" one is used
* for everything else that needs to be scheduled.<br>
* There also is an {@link #_aiScheduledThreadPool "ai"} {@link ScheduledThreadPoolExecutor ScheduledThreadPool} used for AI Tasks.
* </p>
* <p>
* Tasks can be sent to {@link ScheduledThreadPoolExecutor ScheduledThreadPool} either with:
* <ul>
* <li>{@link #scheduleEffect(Runnable, long, TimeUnit)} and {@link #scheduleEffect(Runnable, long)} : for effects Tasks that needs to be executed only once.</li>
* <li>{@link #scheduleGeneral(Runnable, long, TimeUnit)} and {@link #scheduleGeneral(Runnable, long)} : for scheduled Tasks that needs to be executed once.</li>
* <li>{@link #scheduleAi(Runnable, long, TimeUnit)} and {@link #scheduleAi(Runnable, long)} : for AI Tasks that needs to be executed once</li>
* <li>Scheduled pool keeps a track about incoming, future events.</li>
* <li>Instant pool handles short-life events.</li>
* </ul>
* or
* <ul>
* <li>{@link #scheduleEffectAtFixedRate(Runnable, long, long, TimeUnit)} and {@link #scheduleEffectAtFixedRate(Runnable, long, long)} : for effects Tasks that needs to be executed periodicaly.</li>
* <li>{@link #scheduleGeneralAtFixedRate(Runnable, long, long, TimeUnit)} and {@link #scheduleGeneralAtFixedRate(Runnable, long, long)} : for scheduled Tasks that needs to be executed periodicaly.</li>
* <li>{@link #scheduleAiAtFixedRate(Runnable, long, long, TimeUnit)} and {@link #scheduleAiAtFixedRate(Runnable, long, long)} : for AI Tasks that needs to be executed periodicaly</li>
* </ul>
* </p>
* <p>
* For all Tasks that should be executed with no delay asynchronously in a ThreadPool there also are usual {@link ThreadPoolExecutor ThreadPools} that can grow/shrink according to their load.:
* <ul>
* <li>{@link #_generalPacketsThreadPool GeneralPackets} where most packets handler are executed.</li>
* <li>{@link #_ioPacketsThreadPool I/O Packets} where all the i/o packets are executed.</li>
* <li>There will be an AI ThreadPool where AI events should be executed</li>
* <li>A general ThreadPool where everything else that needs to run asynchronously with no delay should be executed updates, SQL updates/inserts...)?</li>
* </ul>
* </p>
* @author -Wooden-
*/
public class ThreadPoolManager
public final class ThreadPoolManager
{
private static final Logger LOGGER = Logger.getLogger(ThreadPoolManager.class.getName());
protected static final Logger LOG = Logger.getLogger(ThreadPoolManager.class.getName());
public static final class RunnableWrapper implements Runnable
{
private final Runnable _r;
private static final long MAX_DELAY = TimeUnit.NANOSECONDS.toMillis(Long.MAX_VALUE - System.nanoTime()) / 2;
public RunnableWrapper(Runnable r)
private static int _threadPoolRandomizer;
protected static ScheduledThreadPoolExecutor[] _scheduledPools;
protected static ThreadPoolExecutor[] _instantPools;
/**
* Init the different pools, based on Config. It is launched only once, on Gameserver instance.
*/
public static void init()
{
_r = r;
// Feed scheduled pool.
int poolCount = Config.SCHEDULED_THREAD_POOL_COUNT;
if (poolCount == -1)
{
poolCount = Runtime.getRuntime().availableProcessors();
}
@Override
public final void run()
_scheduledPools = new ScheduledThreadPoolExecutor[poolCount];
for (int i = 0; i < poolCount; i++)
{
try
{
_r.run();
}
catch (Throwable e)
{
final Thread t = Thread.currentThread();
final UncaughtExceptionHandler h = t.getUncaughtExceptionHandler();
if (h != null)
{
h.uncaughtException(t, e);
}
}
}
_scheduledPools[i] = new ScheduledThreadPoolExecutor(Config.THREADS_PER_SCHEDULED_THREAD_POOL);
}
protected ScheduledThreadPoolExecutor _effectsScheduledThreadPool;
protected ScheduledThreadPoolExecutor _generalScheduledThreadPool;
protected ScheduledThreadPoolExecutor _aiScheduledThreadPool;
protected ScheduledThreadPoolExecutor _eventScheduledThreadPool;
private final ThreadPoolExecutor _generalPacketsThreadPool;
private final ThreadPoolExecutor _ioPacketsThreadPool;
private final ThreadPoolExecutor _generalThreadPool;
private final ThreadPoolExecutor _eventThreadPool;
private boolean _shutdown;
public static ThreadPoolManager getInstance()
// Feed instant pool.
poolCount = Config.INSTANT_THREAD_POOL_COUNT;
if (poolCount == -1)
{
return SingletonHolder._instance;
poolCount = Runtime.getRuntime().availableProcessors();
}
protected ThreadPoolManager()
_instantPools = new ThreadPoolExecutor[poolCount];
for (int i = 0; i < poolCount; i++)
{
_effectsScheduledThreadPool = new ScheduledThreadPoolExecutor(Config.THREAD_P_EFFECTS, new PriorityThreadFactory("EffectsSTPool", Thread.NORM_PRIORITY));
_generalScheduledThreadPool = new ScheduledThreadPoolExecutor(Config.THREAD_P_GENERAL, new PriorityThreadFactory("GeneralSTPool", Thread.NORM_PRIORITY));
_eventScheduledThreadPool = new ScheduledThreadPoolExecutor(Config.THREAD_E_EVENTS, new PriorityThreadFactory("EventSTPool", Thread.NORM_PRIORITY));
_ioPacketsThreadPool = new ThreadPoolExecutor(Config.IO_PACKET_THREAD_CORE_SIZE, Integer.MAX_VALUE, 5L, TimeUnit.SECONDS, new LinkedBlockingQueue<>(), new PriorityThreadFactory("I/O Packet Pool", Thread.NORM_PRIORITY + 1));
_generalPacketsThreadPool = new ThreadPoolExecutor(Config.GENERAL_PACKET_THREAD_CORE_SIZE, Config.GENERAL_PACKET_THREAD_CORE_SIZE + 2, 15L, TimeUnit.SECONDS, new LinkedBlockingQueue<>(), new PriorityThreadFactory("Normal Packet Pool", Thread.NORM_PRIORITY + 1));
_generalThreadPool = new ThreadPoolExecutor(Config.GENERAL_THREAD_CORE_SIZE, Config.GENERAL_THREAD_CORE_SIZE + 2, 5L, TimeUnit.SECONDS, new LinkedBlockingQueue<>(), new PriorityThreadFactory("General Pool", Thread.NORM_PRIORITY));
_aiScheduledThreadPool = new ScheduledThreadPoolExecutor(Config.AI_MAX_THREAD, new PriorityThreadFactory("AISTPool", Thread.NORM_PRIORITY));
_eventThreadPool = new ThreadPoolExecutor(Config.EVENT_MAX_THREAD, Config.EVENT_MAX_THREAD + 2, 5L, TimeUnit.SECONDS, new LinkedBlockingQueue<>(), new PriorityThreadFactory("Event Pool", Thread.NORM_PRIORITY));
_instantPools[i] = new ThreadPoolExecutor(Config.THREADS_PER_INSTANT_THREAD_POOL, Config.THREADS_PER_INSTANT_THREAD_POOL, 0, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(100000));
}
scheduleGeneralAtFixedRate(new PurgeTask(), 10, 5, TimeUnit.MINUTES);
// Prestart core threads.
for (ScheduledThreadPoolExecutor threadPool : _scheduledPools)
{
threadPool.prestartAllCoreThreads();
}
for (ThreadPoolExecutor threadPool : _instantPools)
{
threadPool.prestartAllCoreThreads();
}
// Launch purge task.
scheduleAtFixedRate(() ->
{
purge();
}, 600000, 600000);
LOG.info("ThreadPoolManager: Initialized " + getPoolSize(_instantPools) + "/" + getMaximumPoolSize(_instantPools) + " instant thread(s).");
LOG.info("ThreadPoolManager: Initialized " + getPoolSize(_scheduledPools) + "/" + getMaximumPoolSize(_scheduledPools) + " scheduled thread(s).");
}
public static void purge()
{
for (ScheduledThreadPoolExecutor threadPool1 : _scheduledPools)
{
threadPool1.purge();
}
for (ThreadPoolExecutor threadPool2 : _instantPools)
{
threadPool2.purge();
}
}
/**
* Schedules an effect task to be executed after the given delay.
* @param task the task to execute
* @param delay the delay in the given time unit
* @param unit the time unit of the delay parameter
* @return a ScheduledFuture representing pending completion of the task, and whose get() method will throw an exception upon cancellation
* Schedules a one-shot action that becomes enabled after a delay. The pool is chosen based on pools activity.
* @param r : the task to execute.
* @param delay : the time from now to delay execution.
* @return a ScheduledFuture representing pending completion of the task and whose get() method will return null upon completion.
*/
public ScheduledFuture<?> scheduleEffect(Runnable task, long delay, TimeUnit unit)
public static ScheduledFuture<?> schedule(Runnable r, long delay)
{
try
{
return _effectsScheduledThreadPool.schedule(new RunnableWrapper(task), delay, unit);
return getPool(_scheduledPools).schedule(new TaskWrapper(r), validate(delay), TimeUnit.MILLISECONDS);
}
catch (RejectedExecutionException e)
catch (Exception e)
{
return null;
}
}
/**
* Schedules an effect task to be executed after the given delay.
* @param task the task to execute
* @param delay the delay in milliseconds
* @return a ScheduledFuture representing pending completion of the task, and whose get() method will throw an exception upon cancellation
* Schedules a periodic action that becomes enabled after a delay. The pool is chosen based on pools activity.
* @param r : the task to execute.
* @param delay : the time from now to delay execution.
* @param period : the period between successive executions.
* @return a ScheduledFuture representing pending completion of the task and whose get() method will throw an exception upon cancellation.
*/
public ScheduledFuture<?> scheduleEffect(Runnable task, long delay)
{
return scheduleEffect(task, delay, TimeUnit.MILLISECONDS);
}
/**
* Schedules an effect task to be executed at fixed rate.
* @param task the task to execute
* @param initialDelay the initial delay in the given time unit
* @param period the period between executions in the given time unit
* @param unit the time unit of the initialDelay and period parameters
* @return a ScheduledFuture representing pending completion of the task, and whose get() method will throw an exception upon cancellation
*/
public ScheduledFuture<?> scheduleEffectAtFixedRate(Runnable task, long initialDelay, long period, TimeUnit unit)
public static ScheduledFuture<?> scheduleAtFixedRate(Runnable r, long delay, long period)
{
try
{
return _effectsScheduledThreadPool.scheduleAtFixedRate(new RunnableWrapper(task), initialDelay, period, unit);
return getPool(_scheduledPools).scheduleAtFixedRate(new TaskWrapper(r), validate(delay), validate(period), TimeUnit.MILLISECONDS);
}
catch (RejectedExecutionException e)
catch (Exception e)
{
return null; /* shutdown, ignore */
return null;
}
}
/**
* Schedules an effect task to be executed at fixed rate.
* @param task the task to execute
* @param initialDelay the initial delay in milliseconds
* @param period the period between executions in milliseconds
* @return a ScheduledFuture representing pending completion of the task, and whose get() method will throw an exception upon cancellation
* Executes the given task sometime in the future.
* @param r : the task to execute.
*/
public ScheduledFuture<?> scheduleEffectAtFixedRate(Runnable task, long initialDelay, long period)
{
return scheduleEffectAtFixedRate(task, initialDelay, period, TimeUnit.MILLISECONDS);
}
/**
* Schedules a general task to be executed after the given delay.
* @param task the task to execute
* @param delay the delay in the given time unit
* @param unit the time unit of the delay parameter
* @return a ScheduledFuture representing pending completion of the task, and whose get() method will throw an exception upon cancellation
*/
public ScheduledFuture<?> scheduleGeneral(Runnable task, long delay, TimeUnit unit)
public static void execute(Runnable r)
{
try
{
return _generalScheduledThreadPool.schedule(new RunnableWrapper(task), delay, unit);
getPool(_instantPools).execute(new TaskWrapper(r));
}
catch (RejectedExecutionException e)
catch (Exception e)
{
return null; /* shutdown, ignore */
}
}
/**
* Schedules a general task to be executed after the given delay.
* @param task the task to execute
* @param delay the delay in milliseconds
* @return a ScheduledFuture representing pending completion of the task, and whose get() method will throw an exception upon cancellation
*/
public ScheduledFuture<?> scheduleGeneral(Runnable task, long delay)
public static String[] getStats()
{
return scheduleGeneral(task, delay, TimeUnit.MILLISECONDS);
List<String> stats = new ArrayList<>();
for (int i = 0; i < _scheduledPools.length; i++)
{
final ScheduledThreadPoolExecutor threadPool = _scheduledPools[i];
stats.add("Scheduled pool #" + i + ":");
stats.add(" |- ActiveCount: ...... " + threadPool.getActiveCount());
stats.add(" |- CorePoolSize: ..... " + threadPool.getCorePoolSize());
stats.add(" |- PoolSize: ......... " + threadPool.getPoolSize());
stats.add(" |- LargestPoolSize: .. " + threadPool.getLargestPoolSize());
stats.add(" |- MaximumPoolSize: .. " + threadPool.getMaximumPoolSize());
stats.add(" |- CompletedTaskCount: " + threadPool.getCompletedTaskCount());
stats.add(" |- QueuedTaskCount: .. " + threadPool.getQueue().size());
stats.add(" |- TaskCount: ........ " + threadPool.getTaskCount());
stats.add(" | -------");
}
for (int i = 0; i < _instantPools.length; i++)
{
final ThreadPoolExecutor threadPool = _instantPools[i];
stats.add("Scheduled pool #" + i + ":");
stats.add(" |- ActiveCount: ...... " + threadPool.getActiveCount());
stats.add(" |- CorePoolSize: ..... " + threadPool.getCorePoolSize());
stats.add(" |- PoolSize: ......... " + threadPool.getPoolSize());
stats.add(" |- LargestPoolSize: .. " + threadPool.getLargestPoolSize());
stats.add(" |- MaximumPoolSize: .. " + threadPool.getMaximumPoolSize());
stats.add(" |- CompletedTaskCount: " + threadPool.getCompletedTaskCount());
stats.add(" |- QueuedTaskCount: .. " + threadPool.getQueue().size());
stats.add(" |- TaskCount: ........ " + threadPool.getTaskCount());
stats.add(" | -------");
}
return stats.toArray(new String[stats.size()]);
}
/**
* Schedules a general task to be executed at fixed rate.
* @param task the task to execute
* @param initialDelay the initial delay in the given time unit
* @param period the period between executions in the given time unit
* @param unit the time unit of the initialDelay and period parameters
* @return a ScheduledFuture representing pending completion of the task, and whose get() method will throw an exception upon cancellation
* Shutdown thread pooling system correctly. Send different informations.
*/
public ScheduledFuture<?> scheduleGeneralAtFixedRate(Runnable task, long initialDelay, long period, TimeUnit unit)
public static void shutdown()
{
try
{
return _generalScheduledThreadPool.scheduleAtFixedRate(new RunnableWrapper(task), initialDelay, period, unit);
}
catch (RejectedExecutionException e)
System.out.println("ThreadPoolManager: Shutting down.");
for (ScheduledThreadPoolExecutor threadPool : _scheduledPools)
{
return null; /* shutdown, ignore */
threadPool.shutdownNow();
}
for (ThreadPoolExecutor threadPool : _instantPools)
{
threadPool.shutdownNow();
}
}
catch (Throwable t)
{
t.printStackTrace();
}
}
/**
* Schedules a event task to be executed after the given delay.
* @param task the task to execute
* @param delay the delay in the given time unit
* @param unit the time unit of the delay parameter
* @return a ScheduledFuture representing pending completion of the task, and whose get() method will throw an exception upon cancellation
* @param <T> : The pool type.
* @param threadPools : The pool array to check.
* @return the less fed pool.
*/
public ScheduledFuture<?> scheduleEvent(Runnable task, long delay, TimeUnit unit)
private static <T> T getPool(T[] threadPools)
{
try
{
return _eventScheduledThreadPool.schedule(new RunnableWrapper(task), delay, unit);
}
catch (RejectedExecutionException e)
{
return null; /* shutdown, ignore */
}
return threadPools[_threadPoolRandomizer++ % threadPools.length];
}
/**
* Schedules a event task to be executed after the given delay.
* @param task the task to execute
* @param delay the delay in milliseconds
* @return a ScheduledFuture representing pending completion of the task, and whose get() method will throw an exception upon cancellation
* @param delay : The delay to validate.
* @return a secured value, from 0 to MAX_DELAY.
*/
public ScheduledFuture<?> scheduleEvent(Runnable task, long delay)
private static long validate(long delay)
{
return scheduleEvent(task, delay, TimeUnit.MILLISECONDS);
return Math.max(0, Math.min(MAX_DELAY, delay));
}
/**
* Schedules a event task to be executed at fixed rate.
* @param task the task to execute
* @param initialDelay the initial delay in the given time unit
* @param period the period between executions in the given time unit
* @return a ScheduledFuture representing pending completion of the task, and whose get() method will throw an exception upon cancellation
* @param threadPools : The pool array to check.
* @return the overall actual pools size.
*/
public ScheduledFuture<?> scheduleEventAtFixedRate(Runnable task, long initialDelay, long period)
private static long getPoolSize(ThreadPoolExecutor[] threadPools)
{
return scheduleEventAtFixedRate(task, initialDelay, period, TimeUnit.MILLISECONDS);
long result = 0;
for (ThreadPoolExecutor threadPool : threadPools)
{
result += threadPool.getPoolSize();
}
return result;
}
/**
* Schedules a event task to be executed at fixed rate.
* @param task the task to execute
* @param initialDelay the initial delay in the given time unit
* @param period the period between executions in the given time unit
* @param unit the time unit of the initialDelay and period parameters
* @return a ScheduledFuture representing pending completion of the task, and whose get() method will throw an exception upon cancellation
* @param threadPools : The pool array to check.
* @return the overall maximum pools size.
*/
public ScheduledFuture<?> scheduleEventAtFixedRate(Runnable task, long initialDelay, long period, TimeUnit unit)
private static long getMaximumPoolSize(ThreadPoolExecutor[] threadPools)
{
try
long result = 0;
for (ThreadPoolExecutor threadPool : threadPools)
{
return _eventScheduledThreadPool.scheduleAtFixedRate(new RunnableWrapper(task), initialDelay, period, unit);
}
catch (RejectedExecutionException e)
{
return null; /* shutdown, ignore */
}
result += threadPool.getMaximumPoolSize();
}
/**
* Schedules a general task to be executed at fixed rate.
* @param task the task to execute
* @param initialDelay the initial delay in milliseconds
* @param period the period between executions in milliseconds
* @return a ScheduledFuture representing pending completion of the task, and whose get() method will throw an exception upon cancellation
*/
public ScheduledFuture<?> scheduleGeneralAtFixedRate(Runnable task, long initialDelay, long period)
{
return scheduleGeneralAtFixedRate(task, initialDelay, period, TimeUnit.MILLISECONDS);
return result;
}
/**
* Schedules an AI task to be executed after the given delay.
* @param task the task to execute
* @param delay the delay in the given time unit
* @param unit the time unit of the delay parameter
* @return a ScheduledFuture representing pending completion of the task, and whose get() method will throw an exception upon cancellation
*/
public ScheduledFuture<?> scheduleAi(Runnable task, long delay, TimeUnit unit)
public static final class TaskWrapper implements Runnable
{
try
private final Runnable _runnable;
public TaskWrapper(Runnable runnable)
{
return _aiScheduledThreadPool.schedule(new RunnableWrapper(task), delay, unit);
}
catch (RejectedExecutionException e)
{
return null; /* shutdown, ignore */
}
_runnable = runnable;
}
/**
* Schedules an AI task to be executed after the given delay.
* @param task the task to execute
* @param delay the delay in milliseconds
* @return a ScheduledFuture representing pending completion of the task, and whose get() method will throw an exception upon cancellation
*/
public ScheduledFuture<?> scheduleAi(Runnable task, long delay)
{
return scheduleAi(task, delay, TimeUnit.MILLISECONDS);
}
/**
* Schedules a general task to be executed at fixed rate.
* @param task the task to execute
* @param initialDelay the initial delay in the given time unit
* @param period the period between executions in the given time unit
* @param unit the time unit of the initialDelay and period parameters
* @return a ScheduledFuture representing pending completion of the task, and whose get() method will throw an exception upon cancellation
*/
public ScheduledFuture<?> scheduleAiAtFixedRate(Runnable task, long initialDelay, long period, TimeUnit unit)
{
try
{
return _aiScheduledThreadPool.scheduleAtFixedRate(new RunnableWrapper(task), initialDelay, period, unit);
}
catch (RejectedExecutionException e)
{
return null; /* shutdown, ignore */
}
}
/**
* Schedules a general task to be executed at fixed rate.
* @param task the task to execute
* @param initialDelay the initial delay in milliseconds
* @param period the period between executions in milliseconds
* @return a ScheduledFuture representing pending completion of the task, and whose get() method will throw an exception upon cancellation
*/
public ScheduledFuture<?> scheduleAiAtFixedRate(Runnable task, long initialDelay, long period)
{
return scheduleAiAtFixedRate(task, initialDelay, period, TimeUnit.MILLISECONDS);
}
/**
* Executes a packet task sometime in future in another thread.
* @param task the task to execute
*/
public void executePacket(Runnable task)
{
try
{
_generalPacketsThreadPool.execute(task);
}
catch (RejectedExecutionException e)
{
/* shutdown, ignore */
}
}
/**
* Executes an IO packet task sometime in future in another thread.
* @param task the task to execute
*/
public void executeIOPacket(Runnable task)
{
try
{
_ioPacketsThreadPool.execute(task);
}
catch (RejectedExecutionException e)
{
/* shutdown, ignore */
}
}
/**
* Executes a general task sometime in future in another thread.
* @param task the task to execute
*/
public void executeGeneral(Runnable task)
{
try
{
_generalThreadPool.execute(new RunnableWrapper(task));
}
catch (RejectedExecutionException e)
{
/* shutdown, ignore */
}
}
/**
* Executes an AI task sometime in future in another thread.
* @param task the task to execute
*/
public void executeAi(Runnable task)
{
try
{
_aiScheduledThreadPool.execute(new RunnableWrapper(task));
}
catch (RejectedExecutionException e)
{
/* shutdown, ignore */
}
}
/**
* Executes an Event task sometime in future in another thread.
* @param task the task to execute
*/
public void executeEvent(Runnable task)
{
try
{
_eventThreadPool.execute(new RunnableWrapper(task));
}
catch (RejectedExecutionException e)
{
/* shutdown, ignore */
}
}
public StatsSet getStats(String category)
{
final StatsSet StatsSet = new StatsSet();
switch (category)
{
case "EFFECTS":
{
StatsSet.set("ActiveThreads", _effectsScheduledThreadPool.getActiveCount());
StatsSet.set("getCorePoolSize", _effectsScheduledThreadPool.getCorePoolSize());
StatsSet.set("PoolSize", _effectsScheduledThreadPool.getPoolSize());
StatsSet.set("MaximumPoolSize", _effectsScheduledThreadPool.getMaximumPoolSize());
StatsSet.set("CompletedTasks", (int) _effectsScheduledThreadPool.getCompletedTaskCount());
StatsSet.set("ScheduledTasks", _effectsScheduledThreadPool.getQueue().size());
break;
}
case "GENERAL":
{
StatsSet.set("ActiveThreads", _generalScheduledThreadPool.getActiveCount());
StatsSet.set("getCorePoolSizes", _generalScheduledThreadPool.getCorePoolSize());
StatsSet.set("PoolSizes", _generalScheduledThreadPool.getPoolSize());
StatsSet.set("MaximumPoolSizes", _generalScheduledThreadPool.getMaximumPoolSize());
StatsSet.set("CompletedTasks", (int) _generalScheduledThreadPool.getCompletedTaskCount());
StatsSet.set("ScheduledTasks", _generalScheduledThreadPool.getQueue().size());
break;
}
case "AI":
{
StatsSet.set("ActiveThreads", _aiScheduledThreadPool.getActiveCount());
StatsSet.set("getCorePoolSize", _aiScheduledThreadPool.getCorePoolSize());
StatsSet.set("PoolSize", _aiScheduledThreadPool.getPoolSize());
StatsSet.set("MaximumPoolSize", _aiScheduledThreadPool.getMaximumPoolSize());
StatsSet.set("CompletedTasks", (int) _aiScheduledThreadPool.getCompletedTaskCount());
StatsSet.set("ScheduledTasks", _aiScheduledThreadPool.getQueue().size());
break;
}
case "EVENT":
{
StatsSet.set("ActiveThreads", _eventScheduledThreadPool.getActiveCount());
StatsSet.set("getCorePoolSize", _eventScheduledThreadPool.getCorePoolSize());
StatsSet.set("PoolSize", _eventScheduledThreadPool.getPoolSize());
StatsSet.set("MaximumPoolSize", _eventScheduledThreadPool.getMaximumPoolSize());
StatsSet.set("CompletedTasks", (int) _eventScheduledThreadPool.getCompletedTaskCount());
StatsSet.set("ScheduledTasks", _eventScheduledThreadPool.getQueue().size());
break;
}
case "PACKETS":
{
StatsSet.set("ActiveThreads", _generalPacketsThreadPool.getActiveCount());
StatsSet.set("getCorePoolSize", _generalPacketsThreadPool.getCorePoolSize());
StatsSet.set("MaximumPoolSize", _generalPacketsThreadPool.getMaximumPoolSize());
StatsSet.set("LargestPoolSize", _generalPacketsThreadPool.getLargestPoolSize());
StatsSet.set("PoolSize", _generalPacketsThreadPool.getPoolSize());
StatsSet.set("CompletedTasks", (int) _generalPacketsThreadPool.getCompletedTaskCount());
StatsSet.set("QueuedTasks", _generalPacketsThreadPool.getQueue().size());
break;
}
case "IOPACKETS":
{
StatsSet.set("ActiveThreads", _ioPacketsThreadPool.getActiveCount());
StatsSet.set("getCorePoolSize", _ioPacketsThreadPool.getCorePoolSize());
StatsSet.set("MaximumPoolSize", _ioPacketsThreadPool.getMaximumPoolSize());
StatsSet.set("LargestPoolSize", _ioPacketsThreadPool.getLargestPoolSize());
StatsSet.set("PoolSize", _ioPacketsThreadPool.getPoolSize());
StatsSet.set("CompletedTasks", (int) _ioPacketsThreadPool.getCompletedTaskCount());
StatsSet.set("QueuedTasks", _ioPacketsThreadPool.getQueue().size());
break;
}
case "GENERAL_TASKS":
{
StatsSet.set("ActiveThreads", _generalThreadPool.getActiveCount());
StatsSet.set("getCorePoolSize", _generalThreadPool.getCorePoolSize());
StatsSet.set("MaximumPoolSize", _generalThreadPool.getMaximumPoolSize());
StatsSet.set("LargestPoolSize", _generalThreadPool.getLargestPoolSize());
StatsSet.set("PoolSize", _generalThreadPool.getPoolSize());
StatsSet.set("CompletedTasks", (int) _generalThreadPool.getCompletedTaskCount());
StatsSet.set("QueuedTasks", _generalThreadPool.getQueue().size());
break;
}
case "EVENT_TASKS":
{
StatsSet.set("ActiveThreads", _eventThreadPool.getActiveCount());
StatsSet.set("getCorePoolSize", _eventThreadPool.getCorePoolSize());
StatsSet.set("MaximumPoolSize", _eventThreadPool.getMaximumPoolSize());
StatsSet.set("LargestPoolSize", _eventThreadPool.getLargestPoolSize());
StatsSet.set("PoolSize", _eventThreadPool.getPoolSize());
StatsSet.set("CompletedTasks", (int) _eventThreadPool.getCompletedTaskCount());
StatsSet.set("QueuedTasks", _eventThreadPool.getQueue().size());
break;
}
}
return StatsSet;
}
public String[] getStats()
{
return new String[]
{
"STP:",
" + Effects:",
" |- ActiveThreads: " + _effectsScheduledThreadPool.getActiveCount(),
" |- getCorePoolSize: " + _effectsScheduledThreadPool.getCorePoolSize(),
" |- PoolSize: " + _effectsScheduledThreadPool.getPoolSize(),
" |- MaximumPoolSize: " + _effectsScheduledThreadPool.getMaximumPoolSize(),
" |- CompletedTasks: " + _effectsScheduledThreadPool.getCompletedTaskCount(),
" |- ScheduledTasks: " + _effectsScheduledThreadPool.getQueue().size(),
" | -------",
" + General:",
" |- ActiveThreads: " + _generalScheduledThreadPool.getActiveCount(),
" |- getCorePoolSize: " + _generalScheduledThreadPool.getCorePoolSize(),
" |- PoolSize: " + _generalScheduledThreadPool.getPoolSize(),
" |- MaximumPoolSize: " + _generalScheduledThreadPool.getMaximumPoolSize(),
" |- CompletedTasks: " + _generalScheduledThreadPool.getCompletedTaskCount(),
" |- ScheduledTasks: " + _generalScheduledThreadPool.getQueue().size(),
" | -------",
" + AI:",
" |- ActiveThreads: " + _aiScheduledThreadPool.getActiveCount(),
" |- getCorePoolSize: " + _aiScheduledThreadPool.getCorePoolSize(),
" |- PoolSize: " + _aiScheduledThreadPool.getPoolSize(),
" |- MaximumPoolSize: " + _aiScheduledThreadPool.getMaximumPoolSize(),
" |- CompletedTasks: " + _aiScheduledThreadPool.getCompletedTaskCount(),
" |- ScheduledTasks: " + _aiScheduledThreadPool.getQueue().size(),
" | -------",
" + Event:",
" |- ActiveThreads: " + _eventScheduledThreadPool.getActiveCount(),
" |- getCorePoolSize: " + _eventScheduledThreadPool.getCorePoolSize(),
" |- PoolSize: " + _eventScheduledThreadPool.getPoolSize(),
" |- MaximumPoolSize: " + _eventScheduledThreadPool.getMaximumPoolSize(),
" |- CompletedTasks: " + _eventScheduledThreadPool.getCompletedTaskCount(),
" |- ScheduledTasks: " + _eventScheduledThreadPool.getQueue().size(),
"TP:",
" + Packets:",
" |- ActiveThreads: " + _generalPacketsThreadPool.getActiveCount(),
" |- getCorePoolSize: " + _generalPacketsThreadPool.getCorePoolSize(),
" |- MaximumPoolSize: " + _generalPacketsThreadPool.getMaximumPoolSize(),
" |- LargestPoolSize: " + _generalPacketsThreadPool.getLargestPoolSize(),
" |- PoolSize: " + _generalPacketsThreadPool.getPoolSize(),
" |- CompletedTasks: " + _generalPacketsThreadPool.getCompletedTaskCount(),
" |- QueuedTasks: " + _generalPacketsThreadPool.getQueue().size(),
" | -------",
" + I/O Packets:",
" |- ActiveThreads: " + _ioPacketsThreadPool.getActiveCount(),
" |- getCorePoolSize: " + _ioPacketsThreadPool.getCorePoolSize(),
" |- MaximumPoolSize: " + _ioPacketsThreadPool.getMaximumPoolSize(),
" |- LargestPoolSize: " + _ioPacketsThreadPool.getLargestPoolSize(),
" |- PoolSize: " + _ioPacketsThreadPool.getPoolSize(),
" |- CompletedTasks: " + _ioPacketsThreadPool.getCompletedTaskCount(),
" |- QueuedTasks: " + _ioPacketsThreadPool.getQueue().size(),
" | -------",
" + General Tasks:",
" |- ActiveThreads: " + _generalThreadPool.getActiveCount(),
" |- getCorePoolSize: " + _generalThreadPool.getCorePoolSize(),
" |- MaximumPoolSize: " + _generalThreadPool.getMaximumPoolSize(),
" |- LargestPoolSize: " + _generalThreadPool.getLargestPoolSize(),
" |- PoolSize: " + _generalThreadPool.getPoolSize(),
" |- CompletedTasks: " + _generalThreadPool.getCompletedTaskCount(),
" |- QueuedTasks: " + _generalThreadPool.getQueue().size(),
" | -------",
" + Event Tasks:",
" |- ActiveThreads: " + _eventThreadPool.getActiveCount(),
" |- getCorePoolSize: " + _eventThreadPool.getCorePoolSize(),
" |- MaximumPoolSize: " + _eventThreadPool.getMaximumPoolSize(),
" |- LargestPoolSize: " + _eventThreadPool.getLargestPoolSize(),
" |- PoolSize: " + _eventThreadPool.getPoolSize(),
" |- CompletedTasks: " + _eventThreadPool.getCompletedTaskCount(),
" |- QueuedTasks: " + _eventThreadPool.getQueue().size(),
" | -------"
};
}
private static class PriorityThreadFactory implements ThreadFactory
{
private final int _prio;
private final String _name;
private final AtomicInteger _threadNumber = new AtomicInteger(1);
private final ThreadGroup _group;
public PriorityThreadFactory(String name, int prio)
{
_prio = prio;
_name = name;
_group = new ThreadGroup(_name);
}
@Override
public Thread newThread(Runnable r)
{
final Thread t = new Thread(_group, r, _name + "-" + _threadNumber.getAndIncrement());
t.setPriority(_prio);
return t;
}
public ThreadGroup getGroup()
{
return _group;
}
}
public void shutdown()
{
_shutdown = true;
try
{
_effectsScheduledThreadPool.awaitTermination(1, TimeUnit.SECONDS);
_generalScheduledThreadPool.awaitTermination(1, TimeUnit.SECONDS);
_generalPacketsThreadPool.awaitTermination(1, TimeUnit.SECONDS);
_ioPacketsThreadPool.awaitTermination(1, TimeUnit.SECONDS);
_generalThreadPool.awaitTermination(1, TimeUnit.SECONDS);
_eventThreadPool.awaitTermination(1, TimeUnit.SECONDS);
_effectsScheduledThreadPool.shutdown();
_generalScheduledThreadPool.shutdown();
_generalPacketsThreadPool.shutdown();
_ioPacketsThreadPool.shutdown();
_generalThreadPool.shutdown();
_eventThreadPool.shutdown();
LOGGER.info("All ThreadPools are now stopped");
}
catch (InterruptedException e)
{
LOGGER.log(Level.WARNING, "", e);
}
}
public boolean isShutdown()
{
return _shutdown;
}
public void purge()
{
_effectsScheduledThreadPool.purge();
_generalScheduledThreadPool.purge();
_aiScheduledThreadPool.purge();
_eventScheduledThreadPool.purge();
_ioPacketsThreadPool.purge();
_generalPacketsThreadPool.purge();
_generalThreadPool.purge();
_eventThreadPool.purge();
}
public String getPacketStats()
{
final StringBuilder sb = new StringBuilder(1000);
final ThreadFactory tf = _generalPacketsThreadPool.getThreadFactory();
if (tf instanceof PriorityThreadFactory)
{
final PriorityThreadFactory ptf = (PriorityThreadFactory) tf;
final int count = ptf.getGroup().activeCount();
final Thread[] threads = new Thread[count + 2];
ptf.getGroup().enumerate(threads);
sb.append("General Packet Thread Pool:" + Config.EOL + "Tasks in the queue: " + _generalPacketsThreadPool.getQueue().size() + Config.EOL + "Showing threads stack trace:" + Config.EOL + "There should be " + count + " Threads" + Config.EOL);
for (Thread t : threads)
{
if (t == null)
{
continue;
}
sb.append(t.getName());
sb.append(Config.EOL);
for (StackTraceElement ste : t.getStackTrace())
{
sb.append(ste);
sb.append(Config.EOL);
}
}
}
sb.append("Packet Tp stack traces printed.");
sb.append(Config.EOL);
return sb.toString();
}
public String getIOPacketStats()
{
final StringBuilder sb = new StringBuilder(1000);
final ThreadFactory tf = _ioPacketsThreadPool.getThreadFactory();
if (tf instanceof PriorityThreadFactory)
{
final PriorityThreadFactory ptf = (PriorityThreadFactory) tf;
final int count = ptf.getGroup().activeCount();
final Thread[] threads = new Thread[count + 2];
ptf.getGroup().enumerate(threads);
sb.append("I/O Packet Thread Pool:" + Config.EOL + "Tasks in the queue: " + _ioPacketsThreadPool.getQueue().size() + Config.EOL + "Showing threads stack trace:" + Config.EOL + "There should be " + count + " Threads" + Config.EOL);
for (Thread t : threads)
{
if (t == null)
{
continue;
}
sb.append(t.getName());
sb.append(Config.EOL);
for (StackTraceElement ste : t.getStackTrace())
{
sb.append(ste);
sb.append(Config.EOL);
}
}
}
sb.append("Packet Tp stack traces printed." + Config.EOL);
return sb.toString();
}
public String getGeneralStats()
{
final StringBuilder sb = new StringBuilder(1000);
final ThreadFactory tf = _generalThreadPool.getThreadFactory();
if (tf instanceof PriorityThreadFactory)
{
final PriorityThreadFactory ptf = (PriorityThreadFactory) tf;
final int count = ptf.getGroup().activeCount();
final Thread[] threads = new Thread[count + 2];
ptf.getGroup().enumerate(threads);
sb.append("General Thread Pool:" + Config.EOL + "Tasks in the queue: " + _generalThreadPool.getQueue().size() + Config.EOL + "Showing threads stack trace:" + Config.EOL + "There should be " + +count + " Threads" + Config.EOL);
for (Thread t : threads)
{
if (t == null)
{
continue;
}
sb.append(t.getName());
sb.append(Config.EOL);
for (StackTraceElement ste : t.getStackTrace())
{
sb.append(ste);
sb.append(Config.EOL);
}
}
}
sb.append("Packet Tp stack traces printed." + Config.EOL);
return sb.toString();
}
protected class PurgeTask implements Runnable
{
@Override
public void run()
{
_effectsScheduledThreadPool.purge();
_generalScheduledThreadPool.purge();
_aiScheduledThreadPool.purge();
_eventScheduledThreadPool.purge();
}
}
private static class SingletonHolder
try
{
protected static final ThreadPoolManager _instance = new ThreadPoolManager();
_runnable.run();
}
catch (RuntimeException e)
{
LOG.warning("Exception in a Runnable execution:" + e);
}
}
}
}
@@ -728,7 +728,7 @@ public abstract class AbstractAI implements Ctrl
setTarget(target);
final int followRange = range == -1 ? Rnd.get(50, 100) : range;
_followTask = ThreadPoolManager.getInstance().scheduleAiAtFixedRate(() ->
_followTask = ThreadPoolManager.scheduleAtFixedRate(() ->
{
try
{
@@ -203,7 +203,7 @@ public class L2AttackableAI extends L2CharacterAI implements Runnable
// If not idle - create an AI task (schedule onEvtThink repeatedly)
if (_aiTask == null)
{
_aiTask = ThreadPoolManager.getInstance().scheduleAiAtFixedRate(this, 1000, 1000);
_aiTask = ThreadPoolManager.scheduleAtFixedRate(this, 1000, 1000);
}
}
@@ -308,7 +308,7 @@ public class L2CharacterAI extends AbstractAI
if (_actor.isAttackingNow())
{
ThreadPoolManager.getInstance().scheduleGeneral(new CastTask(_actor, skill, target, item, forceUse, dontMove), _actor.getAttackEndTime() - TimeUnit.MILLISECONDS.toNanos(System.currentTimeMillis()));
ThreadPoolManager.schedule(new CastTask(_actor, skill, target, item, forceUse, dontMove), _actor.getAttackEndTime() - TimeUnit.MILLISECONDS.toNanos(System.currentTimeMillis()));
}
else
{
@@ -89,7 +89,7 @@ public class L2DoorAI extends L2CharacterAI
@Override
protected void onEvtAttacked(L2Character attacker)
{
ThreadPoolManager.getInstance().executeGeneral(new onEventAttackedDoorTask((L2DoorInstance) _actor, attacker));
ThreadPoolManager.execute(new onEventAttackedDoorTask((L2DoorInstance) _actor, attacker));
}
@Override
@@ -217,7 +217,7 @@ public class L2FortSiegeGuardAI extends L2CharacterAI implements Runnable
// If not idle - create an AI task (schedule onEvtThink repeatedly)
if (_aiTask == null)
{
_aiTask = ThreadPoolManager.getInstance().scheduleAiAtFixedRate(this, 1000, 1000);
_aiTask = ThreadPoolManager.scheduleAtFixedRate(this, 1000, 1000);
}
}
@@ -204,7 +204,7 @@ public class L2SiegeGuardAI extends L2CharacterAI implements Runnable
// If not idle - create an AI task (schedule onEvtThink repeatedly)
if (_aiTask == null)
{
_aiTask = ThreadPoolManager.getInstance().scheduleAiAtFixedRate(this, 1000, 1000);
_aiTask = ThreadPoolManager.scheduleAtFixedRate(this, 1000, 1000);
}
}
@@ -342,7 +342,7 @@ public class L2SummonAI extends L2PlayableAI implements Runnable
{
if (_avoidTask == null)
{
_avoidTask = ThreadPoolManager.getInstance().scheduleAiAtFixedRate(this, 100, 100);
_avoidTask = ThreadPoolManager.scheduleAtFixedRate(this, 100, 100);
}
}
@@ -33,7 +33,7 @@ public class WarehouseCacheManager
protected WarehouseCacheManager()
{
ThreadPoolManager.getInstance().scheduleAiAtFixedRate(new CacheScheduler(), 120000, 60000);
ThreadPoolManager.scheduleAtFixedRate(new CacheScheduler(), 120000, 60000);
}
public void addCacheTask(L2PcInstance pc)
@@ -331,7 +331,7 @@ public class ClanTable
public void scheduleRemoveClan(int clanId)
{
ThreadPoolManager.getInstance().scheduleGeneral(() ->
ThreadPoolManager.schedule(() ->
{
if (getClan(clanId) == null)
{
@@ -421,11 +421,11 @@ public final class BotReportTable
c.set(Calendar.DAY_OF_YEAR, c.get(Calendar.DAY_OF_YEAR) + 1);
}
ThreadPoolManager.getInstance().scheduleGeneral(new ResetPointTask(), c.getTimeInMillis() - System.currentTimeMillis());
ThreadPoolManager.schedule(new ResetPointTask(), c.getTimeInMillis() - System.currentTimeMillis());
}
catch (Exception e)
{
ThreadPoolManager.getInstance().scheduleGeneral(new ResetPointTask(), 24 * 3600 * 1000);
ThreadPoolManager.schedule(new ResetPointTask(), 24 * 3600 * 1000);
LOGGER.log(Level.WARNING, getClass().getSimpleName() + ": Could not properly schedule bot report points reset task. Scheduled in 24 hours.", e);
}
}
@@ -221,14 +221,14 @@ public class ItemTable
if ((raid.getFirstCommandChannelAttacked() != null) && !Config.AUTO_LOOT_RAIDS)
{
item.setOwnerId(raid.getFirstCommandChannelAttacked().getLeaderObjectId());
itemLootShedule = ThreadPoolManager.getInstance().scheduleGeneral(new ResetOwner(item), Config.LOOT_RAIDS_PRIVILEGE_INTERVAL);
itemLootShedule = ThreadPoolManager.schedule(new ResetOwner(item), Config.LOOT_RAIDS_PRIVILEGE_INTERVAL);
item.setItemLootShedule(itemLootShedule);
}
}
else if (!Config.AUTO_LOOT || ((reference instanceof L2EventMonsterInstance) && ((L2EventMonsterInstance) reference).eventDropOnGround()))
{
item.setOwnerId(actor.getObjectId());
itemLootShedule = ThreadPoolManager.getInstance().scheduleGeneral(new ResetOwner(item), 15000);
itemLootShedule = ThreadPoolManager.schedule(new ResetOwner(item), 15000);
item.setItemLootShedule(itemLootShedule);
}
}
@@ -53,7 +53,7 @@ public class BitSetIDFactory extends IdFactory
synchronized (BitSetIDFactory.class)
{
ThreadPoolManager.getInstance().scheduleGeneralAtFixedRate(new BitSetCapacityCheck(), 30000, 30000);
ThreadPoolManager.scheduleAtFixedRate(new BitSetCapacityCheck(), 30000, 30000);
initialize();
}
LOGGER.info(getClass().getSimpleName() + ": " + _freeIds.size() + " id's available.");
@@ -29,7 +29,6 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
@@ -107,7 +106,7 @@ public final class CastleManorManager implements IGameXmlReader, IStorable
// Schedule autosave
if (!Config.ALT_MANOR_SAVE_ALL_ACTIONS)
{
ThreadPoolManager.getInstance().scheduleGeneralAtFixedRate(this::storeMe, Config.ALT_MANOR_SAVE_PERIOD_RATE, Config.ALT_MANOR_SAVE_PERIOD_RATE, TimeUnit.HOURS);
ThreadPoolManager.scheduleAtFixedRate(this::storeMe, Config.ALT_MANOR_SAVE_PERIOD_RATE * 60 * 60 * 1000, Config.ALT_MANOR_SAVE_PERIOD_RATE * 60 * 60 * 1000);
}
// Send debug message
@@ -278,7 +277,7 @@ public final class CastleManorManager implements IGameXmlReader, IStorable
break;
}
// Schedule mode change
ThreadPoolManager.getInstance().scheduleGeneral(this::changeMode, (_nextModeChange.getTimeInMillis() - System.currentTimeMillis()));
ThreadPoolManager.schedule(this::changeMode, (_nextModeChange.getTimeInMillis() - System.currentTimeMillis()));
}
public final void changeMode()
@@ -390,7 +390,7 @@ public class ClanEntryManager
private static void lockPlayer(int playerId)
{
_playerLocked.put(playerId, ThreadPoolManager.getInstance().scheduleGeneral(() ->
_playerLocked.put(playerId, ThreadPoolManager.schedule(() ->
{
_playerLocked.remove(playerId);
}, LOCK_TIME));
@@ -398,7 +398,7 @@ public class ClanEntryManager
private static void lockClan(int clanId)
{
_clanLocked.put(clanId, ThreadPoolManager.getInstance().scheduleGeneral(() ->
_clanLocked.put(clanId, ThreadPoolManager.schedule(() ->
{
_clanLocked.remove(clanId);
}, LOCK_TIME));
@@ -114,7 +114,7 @@ public final class CommissionManager
}
else
{
commissionItem.setSaleEndTask(ThreadPoolManager.getInstance().scheduleGeneral(() -> expireSale(commissionItem), Duration.between(Instant.now(), commissionItem.getEndTime()).toMillis()));
commissionItem.setSaleEndTask(ThreadPoolManager.schedule(() -> expireSale(commissionItem), Duration.between(Instant.now(), commissionItem.getEndTime()).toMillis()));
}
}
}
@@ -259,7 +259,7 @@ public final class CommissionManager
if (rs.next())
{
final CommissionItem commissionItem = new CommissionItem(rs.getLong(1), itemInstance, pricePerUnit, startTime, durationInDays);
final ScheduledFuture<?> saleEndTask = ThreadPoolManager.getInstance().scheduleGeneral(() -> expireSale(commissionItem), Duration.between(Instant.now(), commissionItem.getEndTime()).toMillis());
final ScheduledFuture<?> saleEndTask = ThreadPoolManager.schedule(() -> expireSale(commissionItem), Duration.between(Instant.now(), commissionItem.getEndTime()).toMillis());
commissionItem.setSaleEndTask(saleEndTask);
_commissionItems.put(commissionItem.getCommissionId(), commissionItem);
player.getLastCommissionInfos().put(itemInstance.getId(), new ExResponseCommissionInfo(itemInstance.getId(), pricePerUnit, itemCount, (byte) ((durationInDays - 1) / 2)));
@@ -226,7 +226,7 @@ public class DBSpawnManager
{
LOGGER.info(getClass().getSimpleName() + ": Updated " + npc.getName() + " respawn time to " + Util.formatDate(new Date(respawnTime), "dd.MM.yyyy HH:mm"));
_schedules.put(npc.getId(), ThreadPoolManager.getInstance().scheduleGeneral(new SpawnSchedule(npc.getId()), respawnDelay));
_schedules.put(npc.getId(), ThreadPoolManager.schedule(new SpawnSchedule(npc.getId()), respawnDelay));
updateDb();
}
}
@@ -287,7 +287,7 @@ public class DBSpawnManager
else
{
final long spawnTime = respawnTime - System.currentTimeMillis();
_schedules.put(npcId, ThreadPoolManager.getInstance().scheduleGeneral(new SpawnSchedule(npcId), spawnTime));
_schedules.put(npcId, ThreadPoolManager.schedule(new SpawnSchedule(npcId), spawnTime));
}
_spawns.put(npcId, spawn);
@@ -101,7 +101,7 @@ public final class GraciaSeedsManager
}
else
{
ThreadPoolManager.getInstance().scheduleEffect(new UpdateSoDStateTask(), Config.SOD_STAGE_2_LENGTH - timePast);
ThreadPoolManager.schedule(new UpdateSoDStateTask(), Config.SOD_STAGE_2_LENGTH - timePast);
}
break;
case 3:
@@ -98,7 +98,7 @@ public final class GrandBossManager implements IStorable
{
_log.log(Level.WARNING, getClass().getSimpleName() + ": Error while initializing GrandBossManager: " + e.getMessage(), e);
}
ThreadPoolManager.getInstance().scheduleGeneralAtFixedRate(new GrandBossManagerStoreTask(), 5 * 60 * 1000, 5 * 60 * 1000);
ThreadPoolManager.scheduleAtFixedRate(new GrandBossManagerStoreTask(), 5 * 60 * 1000, 5 * 60 * 1000);
}
public int getBossStatus(int bossId)
@@ -86,7 +86,7 @@ public final class HandysBlockCheckerManager
{
holder.checkAndShuffle();
}
ThreadPoolManager.getInstance().executeGeneral(holder.getEvent().new StartEvent());
ThreadPoolManager.execute(holder.getEvent().new StartEvent());
}
else
{
@@ -364,7 +364,7 @@ public final class HandysBlockCheckerManager
private void schedulePenaltyRemoval(int objId)
{
ThreadPoolManager.getInstance().scheduleGeneral(new PenaltyRemoveTask(objId), 10000);
ThreadPoolManager.schedule(new PenaltyRemoveTask(objId), 10000);
}
/**
@@ -47,7 +47,7 @@ public final class ItemsOnGroundManager implements Runnable
{
if (Config.SAVE_DROPPED_ITEM_INTERVAL > 0)
{
ThreadPoolManager.getInstance().scheduleGeneralAtFixedRate(this, Config.SAVE_DROPPED_ITEM_INTERVAL, Config.SAVE_DROPPED_ITEM_INTERVAL);
ThreadPoolManager.scheduleAtFixedRate(this, Config.SAVE_DROPPED_ITEM_INTERVAL, Config.SAVE_DROPPED_ITEM_INTERVAL);
}
load();
}
@@ -74,11 +74,11 @@ public final class MailManager
if (expiration < System.currentTimeMillis())
{
ThreadPoolManager.getInstance().scheduleGeneral(new MessageDeletionTask(msgId), 10000);
ThreadPoolManager.schedule(new MessageDeletionTask(msgId), 10000);
}
else
{
ThreadPoolManager.getInstance().scheduleGeneral(new MessageDeletionTask(msgId), expiration - System.currentTimeMillis());
ThreadPoolManager.schedule(new MessageDeletionTask(msgId), expiration - System.currentTimeMillis());
}
}
}
@@ -209,7 +209,7 @@ public final class MailManager
receiver.sendPacket(new ExUnReadMailCount(receiver));
}
ThreadPoolManager.getInstance().scheduleGeneral(new MessageDeletionTask(msg.getId()), msg.getExpiration() - System.currentTimeMillis());
ThreadPoolManager.schedule(new MessageDeletionTask(msg.getId()), msg.getExpiration() - System.currentTimeMillis());
}
public final void markAsReadInDb(int msgId)
@@ -111,7 +111,7 @@ public class PremiumManager
*/
private void startExpireTask(L2PcInstance player, long delay)
{
ScheduledFuture<?> task = ThreadPoolManager.getInstance().scheduleEvent(new PremiumExpireTask(player), delay);
ScheduledFuture<?> task = ThreadPoolManager.schedule(new PremiumExpireTask(player), delay);
expiretasks.put(player.getAccountName(), task);
}
@@ -71,7 +71,7 @@ public class ServerRestartManager
if (lastRestart != null)
{
nextRestartTime = new SimpleDateFormat("HH:mm").format(lastRestart.getTime());
ThreadPoolManager.getInstance().scheduleGeneral(new ServerRestartTask(), lastDelay - (Config.SERVER_RESTART_SCHEDULE_COUNTDOWN * 1000));
ThreadPoolManager.schedule(new ServerRestartTask(), lastDelay - (Config.SERVER_RESTART_SCHEDULE_COUNTDOWN * 1000));
_log.info("Scheduled server restart at " + lastRestart.getTime() + ".");
}
}
@@ -301,14 +301,14 @@ public final class WalkingManager implements IGameXmlReader
npc.sendDebugMessage("Starting to move at route '" + routeName + "'");
npc.setIsRunning(node.runToLocation());
npc.getAI().setIntention(CtrlIntention.AI_INTENTION_MOVE_TO, node);
walk.setWalkCheckTask(ThreadPoolManager.getInstance().scheduleAiAtFixedRate(new StartMovingTask(npc, routeName), 60000, 60000)); // start walk check task, for resuming walk after fight
walk.setWalkCheckTask(ThreadPoolManager.scheduleAtFixedRate(new StartMovingTask(npc, routeName), 60000, 60000)); // start walk check task, for resuming walk after fight
_activeRoutes.put(npc.getObjectId(), walk); // register route
}
else
{
npc.sendDebugMessage("Failed to start moving along route '" + routeName + "', scheduled");
ThreadPoolManager.getInstance().scheduleGeneral(new StartMovingTask(npc, routeName), 60000);
ThreadPoolManager.schedule(new StartMovingTask(npc, routeName), 60000);
}
}
else
@@ -455,7 +455,7 @@ public final class WalkingManager implements IGameXmlReader
walk.setLastAction(System.currentTimeMillis());
}
ThreadPoolManager.getInstance().scheduleGeneral(new ArrivedTask(npc, walk), 100 + (node.getDelay() * 1000L));
ThreadPoolManager.schedule(new ArrivedTask(npc, walk), 100 + (node.getDelay() * 1000L));
}
}
}
@@ -56,7 +56,7 @@ public final class ClanWar
_startTime = System.currentTimeMillis();
_state = ClanWarState.BLOOD_DECLARATION;
_cancelTask = ThreadPoolManager.getInstance().scheduleGeneral(() ->
_cancelTask = ThreadPoolManager.schedule(() ->
{
clanWarTimeout();
}, (_startTime + TIME_TO_CANCEL_NON_MUTUAL_CLAN_WAR) - System.currentTimeMillis());
@@ -88,7 +88,7 @@ public final class ClanWar
if ((_startTime + TIME_TO_CANCEL_NON_MUTUAL_CLAN_WAR) > System.currentTimeMillis())
{
_cancelTask = ThreadPoolManager.getInstance().scheduleGeneral(() ->
_cancelTask = ThreadPoolManager.schedule(() ->
{
clanWarTimeout();
}, (_startTime + TIME_TO_CANCEL_NON_MUTUAL_CLAN_WAR) - System.currentTimeMillis());
@@ -104,7 +104,7 @@ public final class ClanWar
}
else
{
ThreadPoolManager.getInstance().scheduleGeneral(() ->
ThreadPoolManager.schedule(() ->
{
ClanTable.getInstance().deleteclanswars(_attackerClanId, _attackedClanId);
}, endTimePeriod);
@@ -200,7 +200,7 @@ public final class ClanWar
_winnerClanId = winnerClan.getId();
_endTime = System.currentTimeMillis();
ThreadPoolManager.getInstance().scheduleGeneral(() ->
ThreadPoolManager.schedule(() ->
{
ClanTable.getInstance().deleteclanswars(cancelor.getId(), winnerClan.getId());
}, (_endTime + TIME_TO_DELETION_AFTER_DEFEAT) - System.currentTimeMillis());
@@ -225,7 +225,7 @@ public final class ClanWar
_state = ClanWarState.TIE;
_endTime = System.currentTimeMillis();
ThreadPoolManager.getInstance().scheduleGeneral(() ->
ThreadPoolManager.schedule(() ->
{
ClanTable.getInstance().deleteclanswars(attackerClan.getId(), attackedClan.getId());
}, (_endTime + TIME_TO_DELETION_AFTER_CANCELLATION) - System.currentTimeMillis());
@@ -63,7 +63,7 @@ public class CreatureContainer
{
if ((_task == null) || _task.isDone())
{
_task = ThreadPoolManager.getInstance().scheduleAiAtFixedRate(this::update, 1000L, 1000L);
_task = ThreadPoolManager.scheduleAtFixedRate(this::update, 1000L, 1000L);
}
}
@@ -351,7 +351,7 @@ public class CursedWeapon implements INamable
{
_player.stopTransformation(true);
ThreadPoolManager.getInstance().scheduleGeneral(() -> _player.transform(transformationId, true), 500);
ThreadPoolManager.schedule(() -> _player.transform(transformationId, true), 500);
}
else
{
@@ -375,7 +375,7 @@ public class CursedWeapon implements INamable
}
else
{
_removeTask = ThreadPoolManager.getInstance().scheduleGeneralAtFixedRate(new RemoveTask(), _durationLost * 12000L, _durationLost * 12000L);
_removeTask = ThreadPoolManager.scheduleAtFixedRate(new RemoveTask(), _durationLost * 12000L, _durationLost * 12000L);
}
}
@@ -389,7 +389,7 @@ public class CursedWeapon implements INamable
// Start the Life Task
_endTime = System.currentTimeMillis() + (_duration * 60000L);
_removeTask = ThreadPoolManager.getInstance().scheduleGeneralAtFixedRate(new RemoveTask(), _durationLost * 12000L, _durationLost * 12000L);
_removeTask = ThreadPoolManager.scheduleAtFixedRate(new RemoveTask(), _durationLost * 12000L, _durationLost * 12000L);
return true;
}
@@ -103,6 +103,6 @@ public class DropProtection implements Runnable
throw new NullPointerException("Trying to protect dropped item to null owner");
}
_task = ThreadPoolManager.getInstance().scheduleGeneral(this, PROTECTED_MILLIS_TIME);
_task = ThreadPoolManager.schedule(this, PROTECTED_MILLIS_TIME);
}
}
@@ -220,10 +220,10 @@ public class Fishing
_player.rechargeShots(false, false, true);
}
_reelInTask = ThreadPoolManager.getInstance().scheduleGeneral(() ->
_reelInTask = ThreadPoolManager.schedule(() ->
{
_player.getFishing().reelInWithReward();
_startFishingTask = ThreadPoolManager.getInstance().scheduleGeneral(() -> _player.getFishing().castLine(), Rnd.get(baitData.getWaitMin(), baitData.getWaitMax()));
_startFishingTask = ThreadPoolManager.schedule(() -> _player.getFishing().castLine(), Rnd.get(baitData.getWaitMin(), baitData.getWaitMax()));
}, Rnd.get(baitData.getTimeMin(), baitData.getTimeMax()));
_player.stopMove(null);
_player.broadcastPacket(new ExFishingStart(_player, -1, baitData.getLevel(), _baitLocation));
@@ -3131,7 +3131,7 @@ public class L2Clan implements IIdentifiable, INamable
_vars = new ClanVariables(getId());
if (Config.CLAN_VARIABLES_STORE_INTERVAL > 0)
{
ThreadPoolManager.getInstance().scheduleGeneralAtFixedRate(this::storeVariables, Config.CLAN_VARIABLES_STORE_INTERVAL, Config.CLAN_VARIABLES_STORE_INTERVAL);
ThreadPoolManager.scheduleAtFixedRate(this::storeVariables, Config.CLAN_VARIABLES_STORE_INTERVAL, Config.CLAN_VARIABLES_STORE_INTERVAL);
}
}
}
@@ -379,7 +379,7 @@ public class L2Party extends AbstractPlayerGroup
if (_positionBroadcastTask == null)
{
_positionBroadcastTask = ThreadPoolManager.getInstance().scheduleGeneralAtFixedRate(() ->
_positionBroadcastTask = ThreadPoolManager.scheduleAtFixedRate(() ->
{
if (_positionPacket == null)
{
@@ -1084,7 +1084,7 @@ public class L2Party extends AbstractPlayerGroup
}
_changeRequestDistributionType = partyDistributionType;
_changeDistributionTypeAnswers = new HashSet<>();
_changeDistributionTypeRequestTask = ThreadPoolManager.getInstance().scheduleGeneral(() -> finishLootRequest(false), PARTY_DISTRIBUTION_TYPE_REQUEST_TIMEOUT.toMillis());
_changeDistributionTypeRequestTask = ThreadPoolManager.schedule(() -> finishLootRequest(false), PARTY_DISTRIBUTION_TYPE_REQUEST_TIMEOUT.toMillis());
broadcastToPartyMembers(getLeader(), new ExAskModifyPartyLooting(getLeader().getName(), partyDistributionType));
@@ -123,7 +123,7 @@ public class L2Request
{
_isRequestor = isRequestor;
_isAnswerer = !isRequestor;
ThreadPoolManager.getInstance().scheduleGeneral(() -> clear(), REQUEST_TIMEOUT * 1000);
ThreadPoolManager.schedule(() -> clear(), REQUEST_TIMEOUT * 1000);
}
/**
@@ -400,7 +400,7 @@ public class L2Spawn implements IPositionable, IIdentifiable, INamable
// Create a new SpawnTask to launch after the respawn Delay
// ClientScheduler.getInstance().scheduleLow(new SpawnTask(npcId), _respawnDelay);
ThreadPoolManager.getInstance().scheduleGeneral(new SpawnTask(oldNpc), hasRespawnRandom() ? Rnd.get(_respawnMinDelay, _respawnMaxDelay) : _respawnMinDelay);
ThreadPoolManager.schedule(new SpawnTask(oldNpc), hasRespawnRandom() ? Rnd.get(_respawnMinDelay, _respawnMaxDelay) : _respawnMinDelay);
}
}
@@ -215,7 +215,7 @@ public final class L2WorldRegion
}
// then, set a timer to activate the neighbors
_neighborsTask = ThreadPoolManager.getInstance().scheduleGeneral(new NeighborsTask(true), 1000 * Config.GRID_NEIGHBOR_TURNON_TIME);
_neighborsTask = ThreadPoolManager.schedule(new NeighborsTask(true), 1000 * Config.GRID_NEIGHBOR_TURNON_TIME);
}
}
@@ -235,7 +235,7 @@ public final class L2WorldRegion
// start a timer to "suggest" a deactivate to self and neighbors.
// suggest means: first check if a neighbor has L2PcInstances in it. If not, deactivate.
_neighborsTask = ThreadPoolManager.getInstance().scheduleGeneral(new NeighborsTask(false), 1000 * Config.GRID_NEIGHBOR_TURNOFF_TIME);
_neighborsTask = ThreadPoolManager.schedule(new NeighborsTask(false), 1000 * Config.GRID_NEIGHBOR_TURNOFF_TIME);
}
}
@@ -41,7 +41,7 @@ public class MpRewardTask
_creature = creature;
_count = new AtomicInteger(template.getMpRewardTicks());
_value = calculateBaseValue(npc, creature);
_task = ThreadPoolManager.getInstance().scheduleEffectAtFixedRate(this::run, Config.EFFECT_TICK_RATIO, Config.EFFECT_TICK_RATIO);
_task = ThreadPoolManager.scheduleAtFixedRate(this::run, Config.EFFECT_TICK_RATIO, Config.EFFECT_TICK_RATIO);
}
/**
@@ -232,7 +232,7 @@ public class L2Attackable extends L2Npc
{
_commandChannelTimer = new CommandChannelTimer(this);
_commandChannelLastAttack = System.currentTimeMillis();
ThreadPoolManager.getInstance().scheduleGeneral(_commandChannelTimer, 10000); // check for last attack
ThreadPoolManager.schedule(_commandChannelTimer, 10000); // check for last attack
_firstCommandChannelAttacked.broadcastPacket(new CreatureSay(0, ChatType.PARTYROOM_ALL, "", "You have looting rights!")); // TODO: retail msg
}
}
@@ -1100,7 +1100,7 @@ public abstract class L2Character extends L2Object implements ISkillsHolder, IDe
if (getCurrentMp() < mpConsume)
{
// If L2PcInstance doesn't have enough MP, stop the attack
ThreadPoolManager.getInstance().scheduleAi(new NotifyAITask(this, CtrlEvent.EVT_READY_TO_ACT), 1000);
ThreadPoolManager.schedule(new NotifyAITask(this, CtrlEvent.EVT_READY_TO_ACT), 1000);
sendPacket(SystemMessageId.NOT_ENOUGH_MP);
sendPacket(ActionFailed.STATIC_PACKET);
return;
@@ -1118,7 +1118,7 @@ public abstract class L2Character extends L2Object implements ISkillsHolder, IDe
else
{
// Cancel the action because the bow can't be re-use at this moment
ThreadPoolManager.getInstance().scheduleAi(new NotifyAITask(this, CtrlEvent.EVT_READY_TO_ACT), 1000);
ThreadPoolManager.schedule(new NotifyAITask(this, CtrlEvent.EVT_READY_TO_ACT), 1000);
sendPacket(ActionFailed.STATIC_PACKET);
return;
}
@@ -1222,7 +1222,7 @@ public abstract class L2Character extends L2Object implements ISkillsHolder, IDe
}
// Notify AI with EVT_READY_TO_ACT
ThreadPoolManager.getInstance().scheduleAi(new NotifyAITask(this, CtrlEvent.EVT_READY_TO_ACT), timeAtk);
ThreadPoolManager.schedule(new NotifyAITask(this, CtrlEvent.EVT_READY_TO_ACT), timeAtk);
}
}
@@ -1301,7 +1301,7 @@ public abstract class L2Character extends L2Object implements ISkillsHolder, IDe
}
// Create a new hit task with Medium priority
ThreadPoolManager.getInstance().scheduleAi(new HitTask(this, target, damage1, crit1, miss1, attack.hasSoulshot(), shld1), sAtk);
ThreadPoolManager.schedule(new HitTask(this, target, damage1, crit1, miss1, attack.hasSoulshot(), shld1), sAtk);
// Calculate and set the disable delay of the bow in function of the Attack Speed
_disableRangedAttackEndTime = ((sAtk + reuse) / GameTimeController.MILLIS_IN_TICK) + GameTimeController.getInstance().getGameTicks();
@@ -1371,10 +1371,10 @@ public abstract class L2Character extends L2Object implements ISkillsHolder, IDe
}
// Create a new hit task with Medium priority for hit 1
ThreadPoolManager.getInstance().scheduleAi(new HitTask(this, target, damage1, crit1, miss1, attack.hasSoulshot(), shld1), sAtk / 2);
ThreadPoolManager.schedule(new HitTask(this, target, damage1, crit1, miss1, attack.hasSoulshot(), shld1), sAtk / 2);
// Create a new hit task with Medium priority for hit 2 with a higher delay
ThreadPoolManager.getInstance().scheduleAi(new HitTask(this, target, damage2, crit2, miss2, attack.hasSoulshot(), shld2), sAtk);
ThreadPoolManager.schedule(new HitTask(this, target, damage2, crit2, miss2, attack.hasSoulshot(), shld2), sAtk);
// Add those hits to the Server-Client packet Attack
attack.addHit(target, damage1, miss1, crit1, shld1);
@@ -1401,7 +1401,7 @@ public abstract class L2Character extends L2Object implements ISkillsHolder, IDe
damage /= 2;
}
ThreadPoolManager.getInstance().scheduleAi(new HitTask(this, surroundTarget, damage, crit, miss, attack.hasSoulshot(), shld), sAtk / 2);
ThreadPoolManager.schedule(new HitTask(this, surroundTarget, damage, crit, miss, attack.hasSoulshot(), shld), sAtk / 2);
attack.addHit(surroundTarget, damage, miss, crit, shld);
miss1 |= miss;
}
@@ -1421,7 +1421,7 @@ public abstract class L2Character extends L2Object implements ISkillsHolder, IDe
damage /= 2;
}
ThreadPoolManager.getInstance().scheduleAi(new HitTask(this, surroundTarget, damage, crit, miss, attack.hasSoulshot(), shld), sAtk);
ThreadPoolManager.schedule(new HitTask(this, surroundTarget, damage, crit, miss, attack.hasSoulshot(), shld), sAtk);
attack.addHit(surroundTarget, damage, miss, crit, shld);
miss2 |= miss;
}
@@ -1471,7 +1471,7 @@ public abstract class L2Character extends L2Object implements ISkillsHolder, IDe
}
// Create a new hit task with Medium priority
ThreadPoolManager.getInstance().scheduleAi(new HitTask(this, target, damage1, crit1, miss1, attack.hasSoulshot(), shld1), sAtk);
ThreadPoolManager.schedule(new HitTask(this, target, damage1, crit1, miss1, attack.hasSoulshot(), shld1), sAtk);
// Add this hit to the Server-Client packet Attack
attack.addHit(target, damage1, miss1, crit1, shld1);
@@ -1495,7 +1495,7 @@ public abstract class L2Character extends L2Object implements ISkillsHolder, IDe
damage = (int) Formulas.calcAutoAttackDamage(this, surroundTarget, 0, shld, crit, attack.hasSoulshot());
}
ThreadPoolManager.getInstance().scheduleAi(new HitTask(this, surroundTarget, damage, crit, miss, attack.hasSoulshot(), shld), sAtk);
ThreadPoolManager.schedule(new HitTask(this, surroundTarget, damage, crit, miss, attack.hasSoulshot(), shld), sAtk);
attack.addHit(surroundTarget, damage, miss, crit, shld);
miss1 |= miss;
}
@@ -3332,7 +3332,7 @@ public abstract class L2Character extends L2Object implements ISkillsHolder, IDe
if (distFraction > 1)
{
ThreadPoolManager.getInstance().executeAi(() -> getAI().notifyEvent(CtrlEvent.EVT_ARRIVED));
ThreadPoolManager.execute(() -> getAI().notifyEvent(CtrlEvent.EVT_ARRIVED));
return true;
}
@@ -3773,7 +3773,7 @@ public abstract class L2Character extends L2Object implements ISkillsHolder, IDe
// Create a task to notify the AI that L2Character arrives at a check point of the movement
if ((ticksToMove * GameTimeController.MILLIS_IN_TICK) > 3000)
{
ThreadPoolManager.getInstance().scheduleAi(new NotifyAITask(this, CtrlEvent.EVT_ARRIVED_REVALIDATE), 2000);
ThreadPoolManager.schedule(new NotifyAITask(this, CtrlEvent.EVT_ARRIVED_REVALIDATE), 2000);
}
// the CtrlEvent.EVT_ARRIVED will be sent when the character will actually arrive
@@ -3854,7 +3854,7 @@ public abstract class L2Character extends L2Object implements ISkillsHolder, IDe
// Create a task to notify the AI that L2Character arrives at a check point of the movement
if ((ticksToMove * GameTimeController.MILLIS_IN_TICK) > 3000)
{
ThreadPoolManager.getInstance().scheduleAi(new NotifyAITask(this, CtrlEvent.EVT_ARRIVED_REVALIDATE), 2000);
ThreadPoolManager.schedule(new NotifyAITask(this, CtrlEvent.EVT_ARRIVED_REVALIDATE), 2000);
}
// the CtrlEvent.EVT_ARRIVED will be sent when the character will actually arrive
@@ -1216,7 +1216,7 @@ public class L2Npc extends L2Character
public void scheduleDespawn(long delay)
{
ThreadPoolManager.getInstance().scheduleGeneral(() ->
ThreadPoolManager.schedule(() ->
{
if (!isDecayed())
{
@@ -87,7 +87,7 @@ public abstract class L2Vehicle extends L2Character
{
if (_engine != null)
{
ThreadPoolManager.getInstance().scheduleGeneral(_engine, delay);
ThreadPoolManager.schedule(_engine, delay);
}
}
@@ -253,8 +253,8 @@ public class L2ControllableAirShipInstance extends L2AirShipInstance
public void onSpawn()
{
super.onSpawn();
_checkTask = ThreadPoolManager.getInstance().scheduleGeneralAtFixedRate(new CheckTask(), 60000, 10000);
_consumeFuelTask = ThreadPoolManager.getInstance().scheduleGeneralAtFixedRate(new ConsumeFuelTask(), 60000, 60000);
_checkTask = ThreadPoolManager.scheduleAtFixedRate(new CheckTask(), 60000, 10000);
_consumeFuelTask = ThreadPoolManager.scheduleAtFixedRate(new ConsumeFuelTask(), 60000, 60000);
}
@Override
@@ -326,7 +326,7 @@ public class L2ControllableAirShipInstance extends L2AirShipInstance
if (isSpawned() && isEmpty() && !isInDock())
{
// deleteMe() can't be called from CheckTask because task should not cancel itself
ThreadPoolManager.getInstance().executeGeneral(new DecayTask());
ThreadPoolManager.execute(new DecayTask());
}
}
}
@@ -53,8 +53,8 @@ public class L2DecoyInstance extends L2Character
_totalLifeTime = totalLifeTime;
_timeRemaining = _totalLifeTime;
final int skilllevel = getTemplate().getDisplayId() - 13070;
_DecoyLifeTask = ThreadPoolManager.getInstance().scheduleGeneralAtFixedRate(new DecoyLifetime(getOwner(), this), 1000, 1000);
_HateSpam = ThreadPoolManager.getInstance().scheduleGeneralAtFixedRate(new HateSpam(this, SkillData.getInstance().getSkill(5272, skilllevel)), 2000, 5000);
_DecoyLifeTask = ThreadPoolManager.scheduleAtFixedRate(new DecoyLifetime(getOwner(), this), 1000, 1000);
_HateSpam = ThreadPoolManager.scheduleAtFixedRate(new HateSpam(this, SkillData.getInstance().getSkill(5272, skilllevel)), 2000, 5000);
}
@Override
@@ -107,7 +107,7 @@ public final class L2DoorInstance extends L2Character
{
delay += Rnd.get(getTemplate().getRandomTime());
}
ThreadPoolManager.getInstance().scheduleGeneral(new TimerOpen(), delay * 1000);
ThreadPoolManager.schedule(new TimerOpen(), delay * 1000);
}
@Override
@@ -646,7 +646,7 @@ public final class L2DoorInstance extends L2Character
_autoCloseTask = null;
oldTask.cancel(false);
}
_autoCloseTask = ThreadPoolManager.getInstance().scheduleGeneral(new AutoClose(), getTemplate().getCloseTime() * 1000);
_autoCloseTask = ThreadPoolManager.schedule(new AutoClose(), getTemplate().getCloseTime() * 1000);
}
class AutoClose implements Runnable
@@ -681,7 +681,7 @@ public final class L2DoorInstance extends L2Character
{
delay += Rnd.get(getTemplate().getRandomTime());
}
ThreadPoolManager.getInstance().scheduleGeneral(this, delay * 1000);
ThreadPoolManager.schedule(this, delay * 1000);
}
}
@@ -145,7 +145,7 @@ public class L2FortCommanderInstance extends L2DefenderInstance
{
broadcastSay(ChatType.NPC_SHOUT, npcString, npcString.getParamCount() == 1 ? attacker.getName() : null);
setCanTalk(false);
ThreadPoolManager.getInstance().scheduleGeneral(new ScheduleTalkTask(), 10000);
ThreadPoolManager.schedule(new ScheduleTalkTask(), 10000);
}
}
}
@@ -819,7 +819,7 @@ public final class L2PcInstance extends L2Playable
if (_PvPRegTask == null)
{
_PvPRegTask = ThreadPoolManager.getInstance().scheduleGeneralAtFixedRate(new PvPFlagTask(this), 1000, 1000);
_PvPRegTask = ThreadPoolManager.scheduleAtFixedRate(new PvPFlagTask(this), 1000, 1000);
}
}
@@ -2823,7 +2823,7 @@ public final class L2PcInstance extends L2Playable
getAI().setIntention(CtrlIntention.AI_INTENTION_REST);
broadcastPacket(new ChangeWaitType(this, ChangeWaitType.WT_SITTING));
// Schedule a sit down task to wait for the animation to finish
ThreadPoolManager.getInstance().scheduleGeneral(new SitDownTask(this), 2500);
ThreadPoolManager.schedule(new SitDownTask(this), 2500);
setBlockActions(true);
}
}
@@ -2846,7 +2846,7 @@ public final class L2PcInstance extends L2Playable
broadcastPacket(new ChangeWaitType(this, ChangeWaitType.WT_STANDING));
// Schedule a stand up task to wait for the animation to finish
ThreadPoolManager.getInstance().scheduleGeneral(new StandUpTask(this), 2500);
ThreadPoolManager.schedule(new StandUpTask(this), 2500);
}
}
@@ -4303,7 +4303,7 @@ public final class L2PcInstance extends L2Playable
}
if (Config.GAMEGUARD_ENFORCE)
{
ThreadPoolManager.getInstance().scheduleGeneral(new GameGuardCheckTask(this), 30 * 1000);
ThreadPoolManager.schedule(new GameGuardCheckTask(this), 30 * 1000);
}
}
@@ -8515,7 +8515,7 @@ public final class L2PcInstance extends L2Playable
_inventoryDisable = val;
if (val)
{
ThreadPoolManager.getInstance().scheduleGeneral(new InventoryEnableTask(this), 1500);
ThreadPoolManager.schedule(new InventoryEnableTask(this), 1500);
}
}
@@ -9817,7 +9817,7 @@ public final class L2PcInstance extends L2Playable
{
if (_taskWarnUserTakeBreak == null)
{
_taskWarnUserTakeBreak = ThreadPoolManager.getInstance().scheduleGeneralAtFixedRate(new WarnUserTakeBreakTask(this), 3600000, 3600000);
_taskWarnUserTakeBreak = ThreadPoolManager.scheduleAtFixedRate(new WarnUserTakeBreakTask(this), 3600000, 3600000);
}
}
@@ -9843,7 +9843,7 @@ public final class L2PcInstance extends L2Playable
{
if (_taskRentPet == null)
{
_taskRentPet = ThreadPoolManager.getInstance().scheduleGeneralAtFixedRate(new RentPetTask(this), seconds * 1000L, seconds * 1000L);
_taskRentPet = ThreadPoolManager.scheduleAtFixedRate(new RentPetTask(this), seconds * 1000L, seconds * 1000L);
}
}
@@ -9874,7 +9874,7 @@ public final class L2PcInstance extends L2Playable
final int timeinwater = (int) getStat().getValue(Stats.BREATH, 60000);
sendPacket(new SetupGauge(getObjectId(), 2, timeinwater));
_taskWater = ThreadPoolManager.getInstance().scheduleEffectAtFixedRate(new WaterTask(this), timeinwater, 1000);
_taskWater = ThreadPoolManager.scheduleAtFixedRate(new WaterTask(this), timeinwater, 1000);
}
}
@@ -10255,7 +10255,7 @@ public final class L2PcInstance extends L2Playable
{
if (_teleportWatchdog == null)
{
_teleportWatchdog = ThreadPoolManager.getInstance().scheduleGeneral(new TeleportWatchdogTask(this), Config.TELEPORT_WATCHDOG_TIMEOUT * 1000);
_teleportWatchdog = ThreadPoolManager.schedule(new TeleportWatchdogTask(this), Config.TELEPORT_WATCHDOG_TIMEOUT * 1000);
}
}
}
@@ -11145,7 +11145,7 @@ public final class L2PcInstance extends L2Playable
}
if (_fameTask == null)
{
_fameTask = ThreadPoolManager.getInstance().scheduleGeneralAtFixedRate(new FameTask(this, fameFixRate), delay, delay);
_fameTask = ThreadPoolManager.scheduleAtFixedRate(new FameTask(this, fameFixRate), delay, delay);
}
}
@@ -11265,7 +11265,7 @@ public final class L2PcInstance extends L2Playable
_soulTask.cancel(false);
_soulTask = null;
}
_soulTask = ThreadPoolManager.getInstance().scheduleGeneral(new ResetSoulsTask(this), 600000);
_soulTask = ThreadPoolManager.schedule(new ResetSoulsTask(this), 600000);
}
@@ -11608,7 +11608,7 @@ public final class L2PcInstance extends L2Playable
sendPacket(new SetupGauge(3, (getCurrentFeed() * 10000) / getFeedConsume(), (getMaxFeed() * 10000) / getFeedConsume()));
if (!isDead())
{
_mountFeedTask = ThreadPoolManager.getInstance().scheduleGeneralAtFixedRate(new PetFeedTask(this), 10000, 10000);
_mountFeedTask = ThreadPoolManager.scheduleAtFixedRate(new PetFeedTask(this), 10000, 10000);
}
}
else if (_canFeed)
@@ -11618,7 +11618,7 @@ public final class L2PcInstance extends L2Playable
sendPacket(sg);
if (!isDead())
{
_mountFeedTask = ThreadPoolManager.getInstance().scheduleGeneralAtFixedRate(new PetFeedTask(this), 10000, 10000);
_mountFeedTask = ThreadPoolManager.scheduleAtFixedRate(new PetFeedTask(this), 10000, 10000);
}
}
}
@@ -11695,7 +11695,7 @@ public final class L2PcInstance extends L2Playable
public void enteredNoLanding(int delay)
{
_dismountTask = ThreadPoolManager.getInstance().scheduleGeneral(new DismountTask(this), delay * 1000);
_dismountTask = ThreadPoolManager.schedule(new DismountTask(this), delay * 1000);
}
public void exitedNoLanding()
@@ -11816,7 +11816,7 @@ public final class L2PcInstance extends L2Playable
_chargeTask.cancel(false);
_chargeTask = null;
}
_chargeTask = ThreadPoolManager.getInstance().scheduleGeneral(new ResetChargesTask(this), 600000);
_chargeTask = ThreadPoolManager.schedule(new ResetChargesTask(this), 600000);
}
/**
@@ -12881,7 +12881,7 @@ public final class L2PcInstance extends L2Playable
public void startRecoGiveTask()
{
// Create task to give new recommendations
_recoGiveTask = ThreadPoolManager.getInstance().scheduleGeneralAtFixedRate(new RecoGiveTask(this), 7200000, 3600000);
_recoGiveTask = ThreadPoolManager.scheduleAtFixedRate(new RecoGiveTask(this), 7200000, 3600000);
// Store new data
storeRecommendations();
@@ -13810,7 +13810,7 @@ public final class L2PcInstance extends L2Playable
stopOnlineTimeUpdateTask();
}
_onlineTimeUpdateTask = ThreadPoolManager.getInstance().scheduleAiAtFixedRate(this::updateOnlineTime, 60 * 1000L, 60 * 1000L);
_onlineTimeUpdateTask = ThreadPoolManager.scheduleAtFixedRate(this::updateOnlineTime, 60 * 1000L, 60 * 1000L);
}
private void updateOnlineTime()
@@ -1130,7 +1130,7 @@ public class L2PetInstance extends L2Summon
stopFeed();
if (!isDead() && (getOwner().getPet() == this))
{
_feedTask = ThreadPoolManager.getInstance().scheduleGeneralAtFixedRate(new FeedTask(), 10000, 10000);
_feedTask = ThreadPoolManager.scheduleAtFixedRate(new FeedTask(), 10000, 10000);
}
}
@@ -72,7 +72,7 @@ public class L2RaidBossInstance extends L2MonsterInstance
@Override
protected void startMaintenanceTask()
{
_maintenanceTask = ThreadPoolManager.getInstance().scheduleGeneralAtFixedRate(() -> checkAndReturnToSpawn(), 60000, getMaintenanceInterval() + Rnd.get(5000));
_maintenanceTask = ThreadPoolManager.scheduleAtFixedRate(() -> checkAndReturnToSpawn(), 60000, getMaintenanceInterval() + Rnd.get(5000));
}
protected void checkAndReturnToSpawn()
@@ -85,7 +85,7 @@ public class L2ServitorInstance extends L2Summon implements Runnable
super.onSpawn();
if ((_lifeTime > 0) && (_summonLifeTask == null))
{
_summonLifeTask = ThreadPoolManager.getInstance().scheduleGeneralAtFixedRate(this, 0, 5000);
_summonLifeTask = ThreadPoolManager.scheduleAtFixedRate(this, 0, 5000);
}
}
@@ -163,7 +163,7 @@ public class L2SiegeFlagInstance extends L2Npc
// send warning to owners of headquarters that theirs base is under attack
_clan.broadcastToOnlineMembers(SystemMessage.getSystemMessage(SystemMessageId.YOUR_BASE_IS_BEING_ATTACKED));
setCanTalk(false);
ThreadPoolManager.getInstance().scheduleGeneral(new ScheduleTalkTask(), 20000);
ThreadPoolManager.schedule(new ScheduleTalkTask(), 20000);
}
}
}
@@ -153,7 +153,7 @@ public final class L2TamedBeastInstance extends L2FeedableBeastInstance
{
_durationCheckTask.cancel(true);
}
_durationCheckTask = ThreadPoolManager.getInstance().scheduleGeneralAtFixedRate(new CheckDuration(this), DURATION_CHECK_INTERVAL, DURATION_CHECK_INTERVAL);
_durationCheckTask = ThreadPoolManager.scheduleAtFixedRate(new CheckDuration(this), DURATION_CHECK_INTERVAL, DURATION_CHECK_INTERVAL);
}
}
@@ -217,10 +217,10 @@ public final class L2TamedBeastInstance extends L2FeedableBeastInstance
int delay = 100;
for (Skill skill : _beastSkills)
{
ThreadPoolManager.getInstance().scheduleGeneral(new buffCast(skill), delay);
ThreadPoolManager.schedule(new buffCast(skill), delay);
delay += (100 + skill.getHitTime());
}
ThreadPoolManager.getInstance().scheduleGeneral(new buffCast(null), delay);
ThreadPoolManager.schedule(new buffCast(null), delay);
}
private class buffCast implements Runnable
@@ -284,7 +284,7 @@ public final class L2TamedBeastInstance extends L2FeedableBeastInstance
{
_buffTask.cancel(true);
}
_buffTask = ThreadPoolManager.getInstance().scheduleGeneralAtFixedRate(new CheckOwnerBuffs(this, totalBuffsAvailable), BUFF_INTERVAL, BUFF_INTERVAL);
_buffTask = ThreadPoolManager.scheduleAtFixedRate(new CheckOwnerBuffs(this, totalBuffsAvailable), BUFF_INTERVAL, BUFF_INTERVAL);
}
}
else
@@ -77,7 +77,7 @@ public final class L2TrapInstance extends L2Npc
_remainingTime = _lifeTime;
if (_skill != null)
{
_trapTask = ThreadPoolManager.getInstance().scheduleGeneralAtFixedRate(new TrapTask(this), TICK, TICK);
_trapTask = ThreadPoolManager.scheduleAtFixedRate(new TrapTask(this), TICK, TICK);
}
}
@@ -341,7 +341,7 @@ public final class L2TrapInstance extends L2Npc
EventDispatcher.getInstance().notifyEventAsync(new OnTrapAction(this, target, TrapAction.TRAP_TRIGGERED), this);
ThreadPoolManager.getInstance().scheduleGeneral(new TrapTriggerTask(this), 500);
ThreadPoolManager.schedule(new TrapTriggerTask(this), 500);
}
public void unSummon()
@@ -55,7 +55,7 @@ public abstract class AbstractRequest
public void scheduleTimeout(long delay)
{
_timeOutTask = ThreadPoolManager.getInstance().scheduleGeneral(this::onTimeout, delay);
_timeOutTask = ThreadPoolManager.schedule(this::onTimeout, delay);
}
public boolean isTimeout()
@@ -216,7 +216,7 @@ public class CharStatus
final int period = Formulas.getRegeneratePeriod(getActiveChar());
// Create the HP/MP/CP Regeneration task
_regTask = ThreadPoolManager.getInstance().scheduleEffectAtFixedRate(new RegenTask(), period, period);
_regTask = ThreadPoolManager.scheduleAtFixedRate(new RegenTask(), period, period);
}
}
@@ -48,7 +48,7 @@ public final class CommandChannelTimer implements Runnable
}
else
{
ThreadPoolManager.getInstance().scheduleGeneral(this, 10000); // 10sec
ThreadPoolManager.schedule(this, 10000); // 10sec
}
}
@@ -91,7 +91,7 @@ public class RandomAnimationTask implements Runnable
final int interval = Rnd.get(minWait, maxWait) * 1000;
// Create a RandomAnimation Task that will be launched after the calculated delay
ThreadPoolManager.getInstance().scheduleGeneral(this, interval);
ThreadPoolManager.schedule(this, interval);
}
/**
@@ -38,7 +38,7 @@ public class TrapTriggerTask implements Runnable
try
{
_trap.doCast(_trap.getSkill());
ThreadPoolManager.getInstance().scheduleGeneral(new TrapUnsummonTask(_trap), _trap.getSkill().getHitTime() + 300);
ThreadPoolManager.schedule(new TrapUnsummonTask(_trap), _trap.getSkill().getHitTime() + 300);
}
catch (Exception e)
{
@@ -51,7 +51,7 @@ public class FlyMoveStartTask implements Runnable
if (!_player.hasRequest(SayuneRequest.class))
{
_player.sendPacket(ExNotifyFlyMoveStart.STATIC_PACKET);
ThreadPoolManager.getInstance().scheduleGeneral(this, 1000L);
ThreadPoolManager.schedule(this, 1000L);
}
}
}
@@ -160,7 +160,7 @@ public final class AutoAnnouncement extends Announcement implements Runnable
_task.cancel(false);
}
_currentState = _repeat;
_task = ThreadPoolManager.getInstance().scheduleGeneral(this, _initial);
_task = ThreadPoolManager.schedule(this, _initial);
}
@Override
@@ -178,7 +178,7 @@ public final class AutoAnnouncement extends Announcement implements Runnable
_currentState--;
}
_task = ThreadPoolManager.getInstance().scheduleGeneral(this, _delay);
_task = ThreadPoolManager.schedule(this, _delay);
}
}
}
@@ -119,7 +119,7 @@ public final class Product
}
if ((_restockTask == null) || _restockTask.isDone())
{
_restockTask = ThreadPoolManager.getInstance().scheduleGeneral(this::restock, getRestockDelay());
_restockTask = ThreadPoolManager.schedule(this::restock, getRestockDelay());
}
final boolean result = _count.addAndGet(-val) >= 0;
save();
@@ -136,7 +136,7 @@ public final class Product
final long remainTime = nextRestockTime - System.currentTimeMillis();
if (remainTime > 0)
{
_restockTask = ThreadPoolManager.getInstance().scheduleGeneral(this::restock, remainTime);
_restockTask = ThreadPoolManager.schedule(this::restock, remainTime);
}
else
{
@@ -52,8 +52,8 @@ public class CubicInstance
private void activate()
{
_skillUseTask = ThreadPoolManager.getInstance().scheduleAiAtFixedRate(this::tryToUseSkill, 0, _template.getDelay() * 1000);
_expireTask = ThreadPoolManager.getInstance().scheduleAi(this::deactivate, _template.getDuration() * 1000);
_skillUseTask = ThreadPoolManager.scheduleAtFixedRate(this::tryToUseSkill, 0, _template.getDelay() * 1000);
_expireTask = ThreadPoolManager.schedule(this::deactivate, _template.getDuration() * 1000);
}
public void deactivate()
@@ -306,7 +306,7 @@ public final class BlockCheckerEngine
_abnormalEnd = true;
ThreadPoolManager.getInstance().executeGeneral(new EndEvent());
ThreadPoolManager.execute(new EndEvent());
if (Config.DEBUG)
{
@@ -429,7 +429,7 @@ public final class BlockCheckerEngine
}
_isStarted = true;
// Spawn the blocks
ThreadPoolManager.getInstance().executeGeneral(new SpawnRound(16, 1));
ThreadPoolManager.execute(new SpawnRound(16, 1));
// Start up player parameters
setUpPlayers();
// Set the started time
@@ -463,15 +463,15 @@ public final class BlockCheckerEngine
{
case 1:
// Schedule second spawn round
_task = ThreadPoolManager.getInstance().scheduleGeneral(new SpawnRound(20, 2), 60000);
_task = ThreadPoolManager.schedule(new SpawnRound(20, 2), 60000);
break;
case 2:
// Schedule third spawn round
_task = ThreadPoolManager.getInstance().scheduleGeneral(new SpawnRound(14, 3), 60000);
_task = ThreadPoolManager.schedule(new SpawnRound(14, 3), 60000);
break;
case 3:
// Schedule Event End Count Down
_task = ThreadPoolManager.getInstance().scheduleGeneral(new EndEvent(), 180000);
_task = ThreadPoolManager.schedule(new EndEvent(), 180000);
break;
}
// random % 2, if == 0 will spawn a red block
@@ -530,7 +530,7 @@ public final class BlockCheckerEngine
SpawnTable.getInstance().addNewSpawn(girlSpawn, false);
girlSpawn.init();
// Schedule his deletion after 9 secs of spawn
ThreadPoolManager.getInstance().scheduleGeneral(new CarryingGirlUnspawn(girlSpawn), 9000);
ThreadPoolManager.schedule(new CarryingGirlUnspawn(girlSpawn), 9000);
}
catch (Exception e)
{
@@ -573,7 +573,7 @@ public final class BlockCheckerEngine
/*
* private class CountDown implements Runnable {
* @Override public void run() { _holder.broadCastPacketToTeam(SystemMessage.getSystemMessage(SystemMessageId.BLOCK_CHECKER_WILL_END_IN_5_SECONDS)); ThreadPoolManager.getInstance().scheduleGeneral(new EndEvent(), 5000); } }
* @Override public void run() { _holder.broadCastPacketToTeam(SystemMessage.getSystemMessage(SystemMessageId.BLOCK_CHECKER_WILL_END_IN_5_SECONDS)); ThreadPoolManager.schedule(new EndEvent(), 5000); } }
*/
/**
@@ -166,11 +166,11 @@ public final class Castle extends AbstractResidence
final long currentTime = System.currentTimeMillis();
if (_endDate > currentTime)
{
ThreadPoolManager.getInstance().scheduleGeneral(new FunctionTask(cwh), _endDate - currentTime);
ThreadPoolManager.schedule(new FunctionTask(cwh), _endDate - currentTime);
}
else
{
ThreadPoolManager.getInstance().scheduleGeneral(new FunctionTask(cwh), 0);
ThreadPoolManager.schedule(new FunctionTask(cwh), 0);
}
}
@@ -204,7 +204,7 @@ public final class Castle extends AbstractResidence
{
ClanTable.getInstance().getClan(getOwnerId()).getWarehouse().destroyItemByItemId("CS_function_fee", Inventory.ADENA_ID, fee, null, null);
}
ThreadPoolManager.getInstance().scheduleGeneral(new FunctionTask(true), getRate());
ThreadPoolManager.schedule(new FunctionTask(true), getRate());
}
else
{
@@ -263,7 +263,7 @@ public final class ClanHall extends AbstractResidence
final int failDays = getCostFailDay();
final long time = failDays > 0 ? (failDays > 8 ? Instant.now().toEpochMilli() : Instant.ofEpochMilli(getPaidUntil()).plus(Duration.ofDays(failDays + 1)).toEpochMilli()) : getPaidUntil();
_checkPaymentTask = ThreadPoolManager.getInstance().scheduleGeneral(new CheckPaymentTask(), time - System.currentTimeMillis());
_checkPaymentTask = ThreadPoolManager.schedule(new CheckPaymentTask(), time - System.currentTimeMillis());
}
else
{
@@ -363,7 +363,7 @@ public final class ClanHall extends AbstractResidence
}
else
{
_checkPaymentTask = ThreadPoolManager.getInstance().scheduleGeneral(new CheckPaymentTask(), 1, TimeUnit.DAYS);
_checkPaymentTask = ThreadPoolManager.schedule(new CheckPaymentTask(), 24 * 60 * 60 * 1000); // 1 day
final SystemMessage sm = SystemMessage.getSystemMessage(SystemMessageId.PAYMENT_FOR_YOUR_CLAN_HALL_HAS_NOT_BEEN_MADE_PLEASE_MAKE_PAYMENT_TO_YOUR_CLAN_WAREHOUSE_BY_S1_TOMORROW);
sm.addInt(getLease());
clan.broadcastToOnlineMembers(sm);
@@ -373,7 +373,7 @@ public final class ClanHall extends AbstractResidence
{
clan.getWarehouse().destroyItem("Clan Hall Lease", Inventory.ADENA_ID, getLease(), null, null);
setPaidUntil(Instant.ofEpochMilli(getPaidUntil()).plus(Duration.ofDays(7)).toEpochMilli());
_checkPaymentTask = ThreadPoolManager.getInstance().scheduleGeneral(new CheckPaymentTask(), getPaidUntil() - System.currentTimeMillis());
_checkPaymentTask = ThreadPoolManager.schedule(new CheckPaymentTask(), getPaidUntil() - System.currentTimeMillis());
updateDB();
}
}
@@ -99,7 +99,7 @@ public class Duel
broadcastToTeam2(sm);
}
// Schedule duel start
ThreadPoolManager.getInstance().scheduleGeneral(new ScheduleStartDuelTask(this), 3000);
ThreadPoolManager.schedule(new ScheduleStartDuelTask(this), 3000);
}
public static class PlayerCondition
@@ -207,14 +207,14 @@ public class Duel
}
case Continue:
{
ThreadPoolManager.getInstance().scheduleGeneral(this, 1000);
ThreadPoolManager.schedule(this, 1000);
break;
}
default:
{
setFinished(true);
playKneelAnimation();
ThreadPoolManager.getInstance().scheduleGeneral(new ScheduleEndDuelTask(_duel, _duel.checkEndDuelCondition()), 5000);
ThreadPoolManager.schedule(new ScheduleEndDuelTask(_duel, _duel.checkEndDuelCondition()), 5000);
if (getDueldInstance() != null)
{
getDueldInstance().destroy();
@@ -255,11 +255,11 @@ public class Duel
_duel.teleportPlayers();
// give players 20 seconds to complete teleport and get ready (its ought to be 30 on offical..)
ThreadPoolManager.getInstance().scheduleGeneral(this, 20000);
ThreadPoolManager.schedule(this, 20000);
}
else if (count > 0) // duel not started yet - continue countdown
{
ThreadPoolManager.getInstance().scheduleGeneral(this, 1000);
ThreadPoolManager.schedule(this, 1000);
}
else
{
@@ -436,7 +436,7 @@ public class Duel
broadcastToTeam2(B04_S01);
// start duelling task
ThreadPoolManager.getInstance().scheduleGeneral(new ScheduleDuelTask(this), 1000);
ThreadPoolManager.schedule(new ScheduleDuelTask(this), 1000);
}
/**
@@ -166,11 +166,11 @@ public final class Fort extends AbstractResidence
final long currentTime = System.currentTimeMillis();
if (_endDate > currentTime)
{
ThreadPoolManager.getInstance().scheduleGeneral(new FunctionTask(cwh), _endDate - currentTime);
ThreadPoolManager.schedule(new FunctionTask(cwh), _endDate - currentTime);
}
else
{
ThreadPoolManager.getInstance().scheduleGeneral(new FunctionTask(cwh), 0);
ThreadPoolManager.schedule(new FunctionTask(cwh), 0);
}
}
@@ -204,7 +204,7 @@ public final class Fort extends AbstractResidence
{
getOwnerClan().getWarehouse().destroyItemByItemId("CS_function_fee", Inventory.ADENA_ID, fee, null, null);
}
ThreadPoolManager.getInstance().scheduleGeneral(new FunctionTask(true), getRate());
ThreadPoolManager.schedule(new FunctionTask(true), getRate());
}
else
{
@@ -273,7 +273,7 @@ public final class Fort extends AbstractResidence
public void endOfSiege(L2Clan clan)
{
ThreadPoolManager.getInstance().executeAi(new endFortressSiege(this, clan));
ThreadPoolManager.execute(new endFortressSiege(this, clan));
}
/**
@@ -594,15 +594,15 @@ public final class Fort extends AbstractResidence
initial = (Config.FS_UPDATE_FRQ * 60000L) - initial;
if ((Config.FS_MAX_OWN_TIME <= 0) || (getOwnedTime() < (Config.FS_MAX_OWN_TIME * 3600)))
{
_FortUpdater[0] = ThreadPoolManager.getInstance().scheduleGeneralAtFixedRate(new FortUpdater(this, clan, runCount, UpdaterType.PERIODIC_UPDATE), initial, Config.FS_UPDATE_FRQ * 60000L); // Schedule owner tasks to start running
_FortUpdater[0] = ThreadPoolManager.scheduleAtFixedRate(new FortUpdater(this, clan, runCount, UpdaterType.PERIODIC_UPDATE), initial, Config.FS_UPDATE_FRQ * 60000L); // Schedule owner tasks to start running
if (Config.FS_MAX_OWN_TIME > 0)
{
_FortUpdater[1] = ThreadPoolManager.getInstance().scheduleGeneralAtFixedRate(new FortUpdater(this, clan, runCount, UpdaterType.MAX_OWN_TIME), 3600000, 3600000); // Schedule owner tasks to remove owener
_FortUpdater[1] = ThreadPoolManager.scheduleAtFixedRate(new FortUpdater(this, clan, runCount, UpdaterType.MAX_OWN_TIME), 3600000, 3600000); // Schedule owner tasks to remove owener
}
}
else
{
_FortUpdater[1] = ThreadPoolManager.getInstance().scheduleGeneral(new FortUpdater(this, clan, 0, UpdaterType.MAX_OWN_TIME), 60000); // Schedule owner tasks to remove owner
_FortUpdater[1] = ThreadPoolManager.schedule(new FortUpdater(this, clan, 0, UpdaterType.MAX_OWN_TIME), 60000); // Schedule owner tasks to remove owner
}
}
else
@@ -836,10 +836,10 @@ public final class Fort extends AbstractResidence
{
_FortUpdater[1].cancel(false);
}
_FortUpdater[0] = ThreadPoolManager.getInstance().scheduleGeneralAtFixedRate(new FortUpdater(this, clan, 0, UpdaterType.PERIODIC_UPDATE), Config.FS_UPDATE_FRQ * 60000L, Config.FS_UPDATE_FRQ * 60000L); // Schedule owner tasks to start running
_FortUpdater[0] = ThreadPoolManager.scheduleAtFixedRate(new FortUpdater(this, clan, 0, UpdaterType.PERIODIC_UPDATE), Config.FS_UPDATE_FRQ * 60000L, Config.FS_UPDATE_FRQ * 60000L); // Schedule owner tasks to start running
if (Config.FS_MAX_OWN_TIME > 0)
{
_FortUpdater[1] = ThreadPoolManager.getInstance().scheduleGeneralAtFixedRate(new FortUpdater(this, clan, 0, UpdaterType.MAX_OWN_TIME), 3600000, 3600000); // Schedule owner tasks to remove owener
_FortUpdater[1] = ThreadPoolManager.scheduleAtFixedRate(new FortUpdater(this, clan, 0, UpdaterType.MAX_OWN_TIME), 3600000, 3600000); // Schedule owner tasks to remove owener
}
}
else
@@ -111,7 +111,7 @@ public class FortSiege implements Siegable
final SystemMessage sm;
if (_time == 3600) // 1hr remains
{
ThreadPoolManager.getInstance().scheduleGeneral(new ScheduleStartSiegeTask(600), 3000000); // Prepare task for 10 minutes left.
ThreadPoolManager.schedule(new ScheduleStartSiegeTask(600), 3000000); // Prepare task for 10 minutes left.
}
else if (_time == 600) // 10min remains
{
@@ -119,49 +119,49 @@ public class FortSiege implements Siegable
sm = SystemMessage.getSystemMessage(SystemMessageId.S1_MINUTE_S_UNTIL_THE_FORTRESS_BATTLE_STARTS);
sm.addInt(10);
announceToPlayer(sm);
ThreadPoolManager.getInstance().scheduleGeneral(new ScheduleStartSiegeTask(300), 300000); // Prepare task for 5 minutes left.
ThreadPoolManager.schedule(new ScheduleStartSiegeTask(300), 300000); // Prepare task for 5 minutes left.
}
else if (_time == 300) // 5min remains
{
sm = SystemMessage.getSystemMessage(SystemMessageId.S1_MINUTE_S_UNTIL_THE_FORTRESS_BATTLE_STARTS);
sm.addInt(5);
announceToPlayer(sm);
ThreadPoolManager.getInstance().scheduleGeneral(new ScheduleStartSiegeTask(60), 240000); // Prepare task for 1 minute left.
ThreadPoolManager.schedule(new ScheduleStartSiegeTask(60), 240000); // Prepare task for 1 minute left.
}
else if (_time == 60) // 1min remains
{
sm = SystemMessage.getSystemMessage(SystemMessageId.S1_MINUTE_S_UNTIL_THE_FORTRESS_BATTLE_STARTS);
sm.addInt(1);
announceToPlayer(sm);
ThreadPoolManager.getInstance().scheduleGeneral(new ScheduleStartSiegeTask(30), 30000); // Prepare task for 30 seconds left.
ThreadPoolManager.schedule(new ScheduleStartSiegeTask(30), 30000); // Prepare task for 30 seconds left.
}
else if (_time == 30) // 30seconds remains
{
sm = SystemMessage.getSystemMessage(SystemMessageId.S1_SECOND_S_UNTIL_THE_FORTRESS_BATTLE_STARTS);
sm.addInt(30);
announceToPlayer(sm);
ThreadPoolManager.getInstance().scheduleGeneral(new ScheduleStartSiegeTask(10), 20000); // Prepare task for 10 seconds left.
ThreadPoolManager.schedule(new ScheduleStartSiegeTask(10), 20000); // Prepare task for 10 seconds left.
}
else if (_time == 10) // 10seconds remains
{
sm = SystemMessage.getSystemMessage(SystemMessageId.S1_SECOND_S_UNTIL_THE_FORTRESS_BATTLE_STARTS);
sm.addInt(10);
announceToPlayer(sm);
ThreadPoolManager.getInstance().scheduleGeneral(new ScheduleStartSiegeTask(5), 5000); // Prepare task for 5 seconds left.
ThreadPoolManager.schedule(new ScheduleStartSiegeTask(5), 5000); // Prepare task for 5 seconds left.
}
else if (_time == 5) // 5seconds remains
{
sm = SystemMessage.getSystemMessage(SystemMessageId.S1_SECOND_S_UNTIL_THE_FORTRESS_BATTLE_STARTS);
sm.addInt(5);
announceToPlayer(sm);
ThreadPoolManager.getInstance().scheduleGeneral(new ScheduleStartSiegeTask(1), 4000); // Prepare task for 1 seconds left.
ThreadPoolManager.schedule(new ScheduleStartSiegeTask(1), 4000); // Prepare task for 1 seconds left.
}
else if (_time == 1) // 1seconds remains
{
sm = SystemMessage.getSystemMessage(SystemMessageId.S1_SECOND_S_UNTIL_THE_FORTRESS_BATTLE_STARTS);
sm.addInt(1);
announceToPlayer(sm);
ThreadPoolManager.getInstance().scheduleGeneral(new ScheduleStartSiegeTask(0), 1000); // Prepare task start siege.
ThreadPoolManager.schedule(new ScheduleStartSiegeTask(0), 1000); // Prepare task start siege.
}
else if (_time == 0)// start siege
{
@@ -274,7 +274,7 @@ public class FortSiege implements Siegable
unspawnSiegeGuard(); // Remove all spawned siege guard from this fort
getFort().resetDoors(); // Respawn door to fort
ThreadPoolManager.getInstance().scheduleGeneral(new ScheduleSuspiciousMerchantSpawn(), FortSiegeManager.getInstance().getSuspiciousMerchantRespawnDelay() * 60 * 1000L); // Prepare 3hr task for suspicious merchant respawn
ThreadPoolManager.schedule(new ScheduleSuspiciousMerchantSpawn(), FortSiegeManager.getInstance().getSuspiciousMerchantRespawnDelay() * 60 * 1000L); // Prepare 3hr task for suspicious merchant respawn
setSiegeDateTime(true); // store suspicious merchant spawn in DB
if (_siegeEnd != null)
@@ -336,7 +336,7 @@ public class FortSiege implements Siegable
getFort().getZone().updateZoneStatusForCharactersInside();
// Schedule a task to prepare auto siege end
_siegeEnd = ThreadPoolManager.getInstance().scheduleGeneral(new ScheduleEndSiegeTask(), FortSiegeManager.getInstance().getSiegeLength() * 60 * 1000L); // Prepare auto end task
_siegeEnd = ThreadPoolManager.schedule(new ScheduleEndSiegeTask(), FortSiegeManager.getInstance().getSiegeLength() * 60 * 1000L); // Prepare auto end task
final SystemMessage sm = SystemMessage.getSystemMessage(SystemMessageId.THE_FORTRESS_BATTLE_S1_HAS_BEGUN);
sm.addCastleId(getFort().getResidenceId());
@@ -672,7 +672,7 @@ public class FortSiege implements Siegable
else if (_siegeRestore == null)
{
getFort().getSiege().announceToPlayer(SystemMessage.getSystemMessage(SystemMessageId.THE_BARRACKS_HAVE_BEEN_SEIZED));
_siegeRestore = ThreadPoolManager.getInstance().scheduleGeneral(new ScheduleSiegeRestore(), FortSiegeManager.getInstance().getCountDownLength() * 60 * 1000L);
_siegeRestore = ThreadPoolManager.schedule(new ScheduleSiegeRestore(), FortSiegeManager.getInstance().getCountDownLength() * 60 * 1000L);
}
else
{
@@ -830,7 +830,7 @@ public class FortSiege implements Siegable
saveFortSiege();
clearSiegeClan(); // remove all clans
// spawn suspicious merchant immediately
ThreadPoolManager.getInstance().executeGeneral(new ScheduleSuspiciousMerchantSpawn());
ThreadPoolManager.execute(new ScheduleSuspiciousMerchantSpawn());
}
else
{
@@ -838,33 +838,33 @@ public class FortSiege implements Siegable
if (getAttackerClans().isEmpty())
{
// no attackers - waiting for suspicious merchant spawn
ThreadPoolManager.getInstance().scheduleGeneral(new ScheduleSuspiciousMerchantSpawn(), delay);
ThreadPoolManager.schedule(new ScheduleSuspiciousMerchantSpawn(), delay);
}
else
{
// preparing start siege task
if (delay > 3600000) // more than hour, how this can happens ? spawn suspicious merchant
{
ThreadPoolManager.getInstance().executeGeneral(new ScheduleSuspiciousMerchantSpawn());
_siegeStartTask = ThreadPoolManager.getInstance().scheduleGeneral(new FortSiege.ScheduleStartSiegeTask(3600), delay - 3600000);
ThreadPoolManager.execute(new ScheduleSuspiciousMerchantSpawn());
_siegeStartTask = ThreadPoolManager.schedule(new FortSiege.ScheduleStartSiegeTask(3600), delay - 3600000);
}
if (delay > 600000) // more than 10 min, spawn suspicious merchant
{
ThreadPoolManager.getInstance().executeGeneral(new ScheduleSuspiciousMerchantSpawn());
_siegeStartTask = ThreadPoolManager.getInstance().scheduleGeneral(new FortSiege.ScheduleStartSiegeTask(600), delay - 600000);
ThreadPoolManager.execute(new ScheduleSuspiciousMerchantSpawn());
_siegeStartTask = ThreadPoolManager.schedule(new FortSiege.ScheduleStartSiegeTask(600), delay - 600000);
}
else if (delay > 300000)
{
_siegeStartTask = ThreadPoolManager.getInstance().scheduleGeneral(new FortSiege.ScheduleStartSiegeTask(300), delay - 300000);
_siegeStartTask = ThreadPoolManager.schedule(new FortSiege.ScheduleStartSiegeTask(300), delay - 300000);
}
else if (delay > 60000)
{
_siegeStartTask = ThreadPoolManager.getInstance().scheduleGeneral(new FortSiege.ScheduleStartSiegeTask(60), delay - 60000);
_siegeStartTask = ThreadPoolManager.schedule(new FortSiege.ScheduleStartSiegeTask(60), delay - 60000);
}
else
{
// lower than 1 min, set to 1 min
_siegeStartTask = ThreadPoolManager.getInstance().scheduleGeneral(new FortSiege.ScheduleStartSiegeTask(60), 0);
_siegeStartTask = ThreadPoolManager.schedule(new FortSiege.ScheduleStartSiegeTask(60), 0);
}
_log.info(getClass().getSimpleName() + ": Siege of " + getFort().getName() + " fort: " + getFort().getSiegeDate().getTime());
@@ -894,7 +894,7 @@ public class FortSiege implements Siegable
}
// Execute siege auto start
_siegeStartTask = ThreadPoolManager.getInstance().scheduleGeneral(new FortSiege.ScheduleStartSiegeTask(3600), 0);
_siegeStartTask = ThreadPoolManager.schedule(new FortSiege.ScheduleStartSiegeTask(3600), 0);
}
/**
@@ -103,35 +103,35 @@ public class Siege implements Siegable
final SystemMessage sm = SystemMessage.getSystemMessage(SystemMessageId.S1_HOUR_S_UNTIL_CASTLE_SIEGE_CONCLUSION);
sm.addInt(2);
announceToPlayer(sm, true);
ThreadPoolManager.getInstance().scheduleGeneral(new ScheduleEndSiegeTask(_castleInst), timeRemaining - 3600000); // Prepare task for 1 hr left.
ThreadPoolManager.schedule(new ScheduleEndSiegeTask(_castleInst), timeRemaining - 3600000); // Prepare task for 1 hr left.
}
else if ((timeRemaining <= 3600000) && (timeRemaining > 600000))
{
final SystemMessage sm = SystemMessage.getSystemMessage(SystemMessageId.S1_MINUTE_S_UNTIL_CASTLE_SIEGE_CONCLUSION);
sm.addInt((int) timeRemaining / 60000);
announceToPlayer(sm, true);
ThreadPoolManager.getInstance().scheduleGeneral(new ScheduleEndSiegeTask(_castleInst), timeRemaining - 600000); // Prepare task for 10 minute left.
ThreadPoolManager.schedule(new ScheduleEndSiegeTask(_castleInst), timeRemaining - 600000); // Prepare task for 10 minute left.
}
else if ((timeRemaining <= 600000) && (timeRemaining > 300000))
{
final SystemMessage sm = SystemMessage.getSystemMessage(SystemMessageId.S1_MINUTE_S_UNTIL_CASTLE_SIEGE_CONCLUSION);
sm.addInt((int) timeRemaining / 60000);
announceToPlayer(sm, true);
ThreadPoolManager.getInstance().scheduleGeneral(new ScheduleEndSiegeTask(_castleInst), timeRemaining - 300000); // Prepare task for 5 minute left.
ThreadPoolManager.schedule(new ScheduleEndSiegeTask(_castleInst), timeRemaining - 300000); // Prepare task for 5 minute left.
}
else if ((timeRemaining <= 300000) && (timeRemaining > 10000))
{
final SystemMessage sm = SystemMessage.getSystemMessage(SystemMessageId.S1_MINUTE_S_UNTIL_CASTLE_SIEGE_CONCLUSION);
sm.addInt((int) timeRemaining / 60000);
announceToPlayer(sm, true);
ThreadPoolManager.getInstance().scheduleGeneral(new ScheduleEndSiegeTask(_castleInst), timeRemaining - 10000); // Prepare task for 10 seconds count down
ThreadPoolManager.schedule(new ScheduleEndSiegeTask(_castleInst), timeRemaining - 10000); // Prepare task for 10 seconds count down
}
else if ((timeRemaining <= 10000) && (timeRemaining > 0))
{
final SystemMessage sm = SystemMessage.getSystemMessage(SystemMessageId.THIS_CASTLE_SIEGE_WILL_END_IN_S1_SECOND_S);
sm.addInt((int) timeRemaining / 1000);
announceToPlayer(sm, true);
ThreadPoolManager.getInstance().scheduleGeneral(new ScheduleEndSiegeTask(_castleInst), timeRemaining); // Prepare task for second count down
ThreadPoolManager.schedule(new ScheduleEndSiegeTask(_castleInst), timeRemaining); // Prepare task for second count down
}
else
{
@@ -170,7 +170,7 @@ public class Siege implements Siegable
final long regTimeRemaining = getTimeRegistrationOverDate().getTimeInMillis() - Calendar.getInstance().getTimeInMillis();
if (regTimeRemaining > 0)
{
_scheduledStartSiegeTask = ThreadPoolManager.getInstance().scheduleGeneral(new ScheduleStartSiegeTask(_castleInst), regTimeRemaining);
_scheduledStartSiegeTask = ThreadPoolManager.schedule(new ScheduleStartSiegeTask(_castleInst), regTimeRemaining);
return;
}
endTimeRegistration(true);
@@ -179,7 +179,7 @@ public class Siege implements Siegable
final long timeRemaining = getSiegeDate().getTimeInMillis() - Calendar.getInstance().getTimeInMillis();
if (timeRemaining > 86400000)
{
_scheduledStartSiegeTask = ThreadPoolManager.getInstance().scheduleGeneral(new ScheduleStartSiegeTask(_castleInst), timeRemaining - 86400000); // Prepare task for 24 before siege start to end registration
_scheduledStartSiegeTask = ThreadPoolManager.schedule(new ScheduleStartSiegeTask(_castleInst), timeRemaining - 86400000); // Prepare task for 24 before siege start to end registration
}
else if ((timeRemaining <= 86400000) && (timeRemaining > 13600000))
{
@@ -188,23 +188,23 @@ public class Siege implements Siegable
Broadcast.toAllOnlinePlayers(sm);
_isRegistrationOver = true;
clearSiegeWaitingClan();
_scheduledStartSiegeTask = ThreadPoolManager.getInstance().scheduleGeneral(new ScheduleStartSiegeTask(_castleInst), timeRemaining - 13600000); // Prepare task for 1 hr left before siege start.
_scheduledStartSiegeTask = ThreadPoolManager.schedule(new ScheduleStartSiegeTask(_castleInst), timeRemaining - 13600000); // Prepare task for 1 hr left before siege start.
}
else if ((timeRemaining <= 13600000) && (timeRemaining > 600000))
{
_scheduledStartSiegeTask = ThreadPoolManager.getInstance().scheduleGeneral(new ScheduleStartSiegeTask(_castleInst), timeRemaining - 600000); // Prepare task for 10 minute left.
_scheduledStartSiegeTask = ThreadPoolManager.schedule(new ScheduleStartSiegeTask(_castleInst), timeRemaining - 600000); // Prepare task for 10 minute left.
}
else if ((timeRemaining <= 600000) && (timeRemaining > 300000))
{
_scheduledStartSiegeTask = ThreadPoolManager.getInstance().scheduleGeneral(new ScheduleStartSiegeTask(_castleInst), timeRemaining - 300000); // Prepare task for 5 minute left.
_scheduledStartSiegeTask = ThreadPoolManager.schedule(new ScheduleStartSiegeTask(_castleInst), timeRemaining - 300000); // Prepare task for 5 minute left.
}
else if ((timeRemaining <= 300000) && (timeRemaining > 10000))
{
_scheduledStartSiegeTask = ThreadPoolManager.getInstance().scheduleGeneral(new ScheduleStartSiegeTask(_castleInst), timeRemaining - 10000); // Prepare task for 10 seconds count down
_scheduledStartSiegeTask = ThreadPoolManager.schedule(new ScheduleStartSiegeTask(_castleInst), timeRemaining - 10000); // Prepare task for 10 seconds count down
}
else if ((timeRemaining <= 10000) && (timeRemaining > 0))
{
_scheduledStartSiegeTask = ThreadPoolManager.getInstance().scheduleGeneral(new ScheduleStartSiegeTask(_castleInst), timeRemaining); // Prepare task for second count down
_scheduledStartSiegeTask = ThreadPoolManager.schedule(new ScheduleStartSiegeTask(_castleInst), timeRemaining); // Prepare task for second count down
}
else
{
@@ -523,7 +523,7 @@ public class Siege implements Siegable
// Schedule a task to prepare auto siege end
_siegeEndDate = Calendar.getInstance();
_siegeEndDate.add(Calendar.MINUTE, SiegeManager.getInstance().getSiegeLength());
ThreadPoolManager.getInstance().scheduleGeneral(new ScheduleEndSiegeTask(getCastle()), 1000); // Prepare auto end task
ThreadPoolManager.schedule(new ScheduleEndSiegeTask(getCastle()), 1000); // Prepare auto end task
final SystemMessage sm = SystemMessage.getSystemMessage(SystemMessageId.THE_S1_SIEGE_HAS_STARTED);
sm.addCastleId(getCastle().getResidenceId());
@@ -1095,7 +1095,7 @@ public class Siege implements Siegable
{
_scheduledStartSiegeTask.cancel(false);
}
_scheduledStartSiegeTask = ThreadPoolManager.getInstance().scheduleGeneral(new Siege.ScheduleStartSiegeTask(getCastle()), 1000);
_scheduledStartSiegeTask = ThreadPoolManager.schedule(new Siege.ScheduleStartSiegeTask(getCastle()), 1000);
}
/**
@@ -1413,7 +1413,7 @@ public class Siege implements Siegable
if (_scheduledStartSiegeTask != null)
{
_scheduledStartSiegeTask.cancel(true);
_scheduledStartSiegeTask = ThreadPoolManager.getInstance().scheduleGeneral(new Siege.ScheduleStartSiegeTask(getCastle()), 1000);
_scheduledStartSiegeTask = ThreadPoolManager.schedule(new Siege.ScheduleStartSiegeTask(getCastle()), 1000);
}
try (Connection con = DatabaseFactory.getInstance().getConnection();
@@ -115,7 +115,7 @@ public class EventScheduler
if (timeSchedule <= (30 * 1000))
{
LOGGER.warning("Wrong reschedule for " + _eventManager.getClass().getSimpleName() + " end up run in " + (timeSchedule / 1000) + " seconds!");
ThreadPoolManager.getInstance().scheduleEvent(this::startScheduler, timeSchedule + 1000);
ThreadPoolManager.schedule(this::startScheduler, timeSchedule + 1000);
return;
}
@@ -124,14 +124,14 @@ public class EventScheduler
_task.cancel(false);
}
_task = ThreadPoolManager.getInstance().scheduleEvent(() ->
_task = ThreadPoolManager.schedule(() ->
{
run();
updateLastRun();
if (isRepeating())
{
ThreadPoolManager.getInstance().scheduleEvent(this::startScheduler, 1000);
ThreadPoolManager.schedule(this::startScheduler, 1000);
}
}, timeSchedule);
}
@@ -17,7 +17,6 @@
package com.l2jmobius.gameserver.model.events;
import java.util.Queue;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
@@ -116,7 +115,7 @@ public final class EventDispatcher
if (hasListeners)
{
ThreadPoolManager.getInstance().executeEvent(() -> notifyEventToMultipleContainers(event, containers, null));
ThreadPoolManager.execute(() -> notifyEventToMultipleContainers(event, containers, null));
}
}
@@ -130,22 +129,7 @@ public final class EventDispatcher
{
if (Containers.Global().hasListener(event.getType()) || container.hasListener(event.getType()))
{
ThreadPoolManager.getInstance().scheduleEvent(() -> notifyEvent(event, container, null), delay);
}
}
/**
* Scheduling current listener notification asynchronously after specified delay.
* @param event
* @param container
* @param delay
* @param unit
*/
public void notifyEventAsyncDelayed(IBaseEvent event, ListenersContainer container, long delay, TimeUnit unit)
{
if (Containers.Global().hasListener(event.getType()) || container.hasListener(event.getType()))
{
ThreadPoolManager.getInstance().scheduleEvent(() -> notifyEvent(event, container, null), delay, unit);
ThreadPoolManager.schedule(() -> notifyEvent(event, container, null), delay);
}
}
@@ -58,7 +58,7 @@ public class TimerHolder<T> implements Runnable
_eventScript = eventScript;
_cancelScript = cancelScript;
_postExecutor = postExecutor;
_task = isRepeating ? ThreadPoolManager.getInstance().scheduleEventAtFixedRate(this, _time, _time) : ThreadPoolManager.getInstance().scheduleEvent(this, _time);
_task = isRepeating ? ThreadPoolManager.scheduleAtFixedRate(this, _time, _time) : ThreadPoolManager.schedule(this, _time);
TimersManager.getInstance().registerTimer(this);
}
@@ -290,7 +290,7 @@ public final class Instance implements IIdentifiable, INamable
}
else if ((emptyTime >= 0) && (_emptyDestroyTask == null) && (getRemainingTime() < emptyTime))
{
_emptyDestroyTask = ThreadPoolManager.getInstance().scheduleGeneral(this::destroy, emptyTime);
_emptyDestroyTask = ThreadPoolManager.schedule(this::destroy, emptyTime);
}
}
}
@@ -684,11 +684,11 @@ public final class Instance implements IIdentifiable, INamable
sendWorldDestroyMessage(minutes);
if (minutes <= 5) // Message 1 minute before destroy
{
_cleanUpTask = ThreadPoolManager.getInstance().scheduleGeneral(this::cleanUp, millis - 60000);
_cleanUpTask = ThreadPoolManager.schedule(this::cleanUp, millis - 60000);
}
else // Message 5 minutes before destroy
{
_cleanUpTask = ThreadPoolManager.getInstance().scheduleGeneral(this::cleanUp, millis - (5 * 60000));
_cleanUpTask = ThreadPoolManager.schedule(this::cleanUp, millis - (5 * 60000));
}
}
}
@@ -900,13 +900,13 @@ public final class Instance implements IIdentifiable, INamable
player.sendPacket(sm);
// Start eject task
_ejectDeadTasks.put(player.getObjectId(), ThreadPoolManager.getInstance().scheduleGeneral(() ->
_ejectDeadTasks.put(player.getObjectId(), ThreadPoolManager.schedule(() ->
{
if (player.isDead())
{
ejectPlayer(player.getActingPlayer());
}
}, _template.getEjectTime(), TimeUnit.MINUTES));
}, _template.getEjectTime() * 60 * 1000)); // minutes to milliseconds
}
/**
@@ -1128,12 +1128,12 @@ public final class Instance implements IIdentifiable, INamable
if (getRemainingTime() <= TimeUnit.MINUTES.toMillis(1))
{
sendWorldDestroyMessage(1);
_cleanUpTask = ThreadPoolManager.getInstance().scheduleGeneral(this::destroy, 1, TimeUnit.MINUTES);
_cleanUpTask = ThreadPoolManager.schedule(this::destroy, 60 * 1000); // 1 minute
}
else
{
sendWorldDestroyMessage(5);
_cleanUpTask = ThreadPoolManager.getInstance().scheduleGeneral(this::cleanUp, 5, TimeUnit.MINUTES);
_cleanUpTask = ThreadPoolManager.schedule(this::cleanUp, 5 * 60 * 1000); // 5 minutes
}
}
@@ -400,7 +400,7 @@ public final class ItemAuction
public final void broadcastToAllBidders(IClientOutgoingPacket packet)
{
ThreadPoolManager.getInstance().executeGeneral(() -> broadcastToAllBiddersInternal(packet));
ThreadPoolManager.execute(() -> broadcastToAllBiddersInternal(packet));
}
public final void broadcastToAllBiddersInternal(IClientOutgoingPacket packet)
@@ -331,17 +331,17 @@ public final class ItemAuctionInstance
{
if (currentAuction.getAuctionState() == ItemAuctionState.STARTED)
{
setStateTask(ThreadPoolManager.getInstance().scheduleGeneral(new ScheduleAuctionTask(currentAuction), Math.max(currentAuction.getEndingTime() - System.currentTimeMillis(), 0L)));
setStateTask(ThreadPoolManager.schedule(new ScheduleAuctionTask(currentAuction), Math.max(currentAuction.getEndingTime() - System.currentTimeMillis(), 0L)));
}
else
{
setStateTask(ThreadPoolManager.getInstance().scheduleGeneral(new ScheduleAuctionTask(currentAuction), Math.max(currentAuction.getStartingTime() - System.currentTimeMillis(), 0L)));
setStateTask(ThreadPoolManager.schedule(new ScheduleAuctionTask(currentAuction), Math.max(currentAuction.getStartingTime() - System.currentTimeMillis(), 0L)));
}
LOGGER.info(getClass().getSimpleName() + ": Schedule current auction " + currentAuction.getAuctionId() + " for instance " + _instanceId);
}
else
{
setStateTask(ThreadPoolManager.getInstance().scheduleGeneral(new ScheduleAuctionTask(nextAuction), Math.max(nextAuction.getStartingTime() - System.currentTimeMillis(), 0L)));
setStateTask(ThreadPoolManager.schedule(new ScheduleAuctionTask(nextAuction), Math.max(nextAuction.getStartingTime() - System.currentTimeMillis(), 0L)));
LOGGER.info(getClass().getSimpleName() + ": Schedule next auction " + nextAuction.getAuctionId() + " on " + DATE_FORMAT.format(new Date(nextAuction.getStartingTime())) + " for instance " + _instanceId);
}
}
@@ -429,7 +429,7 @@ public final class ItemAuctionInstance
if (_auction.getScheduledAuctionEndingExtendState() == ItemAuctionExtendState.INITIAL)
{
_auction.setScheduledAuctionEndingExtendState(ItemAuctionExtendState.EXTEND_BY_5_MIN);
setStateTask(ThreadPoolManager.getInstance().scheduleGeneral(this, Math.max(_auction.getEndingTime() - System.currentTimeMillis(), 0L)));
setStateTask(ThreadPoolManager.schedule(this, Math.max(_auction.getEndingTime() - System.currentTimeMillis(), 0L)));
return;
}
break;
@@ -440,7 +440,7 @@ public final class ItemAuctionInstance
if (_auction.getScheduledAuctionEndingExtendState() != ItemAuctionExtendState.EXTEND_BY_3_MIN)
{
_auction.setScheduledAuctionEndingExtendState(ItemAuctionExtendState.EXTEND_BY_3_MIN);
setStateTask(ThreadPoolManager.getInstance().scheduleGeneral(this, Math.max(_auction.getEndingTime() - System.currentTimeMillis(), 0L)));
setStateTask(ThreadPoolManager.schedule(this, Math.max(_auction.getEndingTime() - System.currentTimeMillis(), 0L)));
return;
}
break;
@@ -451,7 +451,7 @@ public final class ItemAuctionInstance
if (_auction.getScheduledAuctionEndingExtendState() != ItemAuctionExtendState.EXTEND_BY_CONFIG_PHASE_B)
{
_auction.setScheduledAuctionEndingExtendState(ItemAuctionExtendState.EXTEND_BY_CONFIG_PHASE_B);
setStateTask(ThreadPoolManager.getInstance().scheduleGeneral(this, Math.max(_auction.getEndingTime() - System.currentTimeMillis(), 0L)));
setStateTask(ThreadPoolManager.schedule(this, Math.max(_auction.getEndingTime() - System.currentTimeMillis(), 0L)));
return;
}
break;
@@ -462,7 +462,7 @@ public final class ItemAuctionInstance
if (_auction.getScheduledAuctionEndingExtendState() != ItemAuctionExtendState.EXTEND_BY_CONFIG_PHASE_A)
{
_auction.setScheduledAuctionEndingExtendState(ItemAuctionExtendState.EXTEND_BY_CONFIG_PHASE_A);
setStateTask(ThreadPoolManager.getInstance().scheduleGeneral(this, Math.max(_auction.getEndingTime() - System.currentTimeMillis(), 0L)));
setStateTask(ThreadPoolManager.schedule(this, Math.max(_auction.getEndingTime() - System.currentTimeMillis(), 0L)));
return;
}
}
@@ -1412,7 +1412,7 @@ public final class L2ItemInstance extends L2Object
return;
}
_consumingMana = true;
ThreadPoolManager.getInstance().scheduleGeneral(new ScheduleConsumeManaTask(this), MANA_CONSUMPTION_RATE);
ThreadPoolManager.schedule(new ScheduleConsumeManaTask(this), MANA_CONSUMPTION_RATE);
}
/**
@@ -1545,7 +1545,7 @@ public final class L2ItemInstance extends L2Object
public final void dropMe(L2Character dropper, int x, int y, int z)
{
ThreadPoolManager.getInstance().executeGeneral(new ItemDropTask(this, dropper, x, y, z));
ThreadPoolManager.execute(new ItemDropTask(this, dropper, x, y, z));
if ((dropper != null) && dropper.isPlayer())
{
// Notify to scripts
@@ -1833,7 +1833,7 @@ public final class L2ItemInstance extends L2Object
{
_lifeTimeTask.cancel(true);
}
_lifeTimeTask = ThreadPoolManager.getInstance().scheduleGeneral(new ScheduleLifeTimeTask(this), getRemainingTime());
_lifeTimeTask = ThreadPoolManager.schedule(new ScheduleLifeTimeTask(this), getRemainingTime());
}
}
@@ -2379,11 +2379,11 @@ public final class L2ItemInstance extends L2Object
final long time = getVisualLifeTime() - System.currentTimeMillis();
if (time > 0)
{
_appearanceLifeTimeTask = ThreadPoolManager.getInstance().scheduleGeneral(this::onVisualLifeTimeEnd, time);
_appearanceLifeTimeTask = ThreadPoolManager.schedule(this::onVisualLifeTimeEnd, time);
}
else
{
ThreadPoolManager.getInstance().executeGeneral(this::onVisualLifeTimeEnd);
ThreadPoolManager.execute(this::onVisualLifeTimeEnd);
}
}
}
@@ -200,7 +200,7 @@ public class Olympiad extends ListenersContainer
if (_validationEnd > Calendar.getInstance().getTimeInMillis())
{
loadNoblesRank();
_scheduledValdationTask = ThreadPoolManager.getInstance().scheduleGeneral(new ValidationEndTask(), getMillisToValidationEnd());
_scheduledValdationTask = ThreadPoolManager.schedule(new ValidationEndTask(), getMillisToValidationEnd());
}
else
{
@@ -357,7 +357,7 @@ public class Olympiad extends ListenersContainer
_scheduledOlympiadEnd.cancel(true);
}
_scheduledOlympiadEnd = ThreadPoolManager.getInstance().scheduleGeneral(new OlympiadEndTask(), getMillisToOlympiadEnd());
_scheduledOlympiadEnd = ThreadPoolManager.schedule(new OlympiadEndTask(), getMillisToOlympiadEnd());
updateCompStatus();
}
@@ -391,7 +391,7 @@ public class Olympiad extends ListenersContainer
_validationEnd = validationEnd.getTimeInMillis() + VALIDATION_PERIOD;
loadNoblesRank();
_scheduledValdationTask = ThreadPoolManager.getInstance().scheduleGeneral(new ValidationEndTask(), getMillisToValidationEnd());
_scheduledValdationTask = ThreadPoolManager.schedule(new ValidationEndTask(), getMillisToValidationEnd());
}
}
@@ -439,7 +439,7 @@ public class Olympiad extends ListenersContainer
LOGGER.info(getClass().getSimpleName() + ": Event starts/started: " + _compStart.getTime());
}
_scheduledCompStart = ThreadPoolManager.getInstance().scheduleGeneral(() ->
_scheduledCompStart = ThreadPoolManager.schedule(() ->
{
if (isOlympiadEnd())
{
@@ -452,19 +452,19 @@ public class Olympiad extends ListenersContainer
LOGGER.info(getClass().getSimpleName() + ": Olympiad Games have started.");
_logResults.info("Result,Player1,Player2,Player1 HP,Player2 HP,Player1 Damage,Player2 Damage,Points,Classed");
_gameManager = ThreadPoolManager.getInstance().scheduleGeneralAtFixedRate(OlympiadGameManager.getInstance(), 30000, 30000);
_gameManager = ThreadPoolManager.scheduleAtFixedRate(OlympiadGameManager.getInstance(), 30000, 30000);
if (Config.ALT_OLY_ANNOUNCE_GAMES)
{
_gameAnnouncer = ThreadPoolManager.getInstance().scheduleGeneralAtFixedRate(new OlympiadAnnouncer(), 30000, 500);
_gameAnnouncer = ThreadPoolManager.scheduleAtFixedRate(new OlympiadAnnouncer(), 30000, 500);
}
final long regEnd = getMillisToCompEnd() - 600000;
if (regEnd > 0)
{
ThreadPoolManager.getInstance().scheduleGeneral(() -> Broadcast.toAllOnlinePlayers(SystemMessage.getSystemMessage(SystemMessageId.THE_OLYMPIAD_REGISTRATION_PERIOD_HAS_ENDED)), regEnd);
ThreadPoolManager.schedule(() -> Broadcast.toAllOnlinePlayers(SystemMessage.getSystemMessage(SystemMessageId.THE_OLYMPIAD_REGISTRATION_PERIOD_HAS_ENDED)), regEnd);
}
_scheduledCompEnd = ThreadPoolManager.getInstance().scheduleGeneral(() ->
_scheduledCompEnd = ThreadPoolManager.schedule(() ->
{
if (isOlympiadEnd())
{
@@ -519,7 +519,7 @@ public class Olympiad extends ListenersContainer
_scheduledOlympiadEnd.cancel(true);
}
_scheduledOlympiadEnd = ThreadPoolManager.getInstance().scheduleGeneral(new OlympiadEndTask(), 0);
_scheduledOlympiadEnd = ThreadPoolManager.schedule(new OlympiadEndTask(), 0);
}
protected long getMillisToValidationEnd()
@@ -608,7 +608,7 @@ public class Olympiad extends ListenersContainer
private void scheduleWeeklyChange()
{
_scheduledWeeklyTask = ThreadPoolManager.getInstance().scheduleGeneralAtFixedRate(() ->
_scheduledWeeklyTask = ThreadPoolManager.scheduleAtFixedRate(() ->
{
addWeeklyPoints();
LOGGER.info(getClass().getSimpleName() + ": Added weekly points to nobles");
@@ -170,7 +170,7 @@ public final class OlympiadGameTask implements Runnable
_game = game;
_state = GameState.BEGIN;
_needAnnounce = false;
ThreadPoolManager.getInstance().executeGeneral(this);
ThreadPoolManager.execute(this);
}
@Override
@@ -341,7 +341,7 @@ public final class OlympiadGameTask implements Runnable
return;
}
}
ThreadPoolManager.getInstance().scheduleGeneral(this, delay * 1000);
ThreadPoolManager.schedule(this, delay * 1000);
}
catch (Exception e)
{
@@ -361,7 +361,7 @@ public final class OlympiadGameTask implements Runnable
_log.log(Level.WARNING, "Exception in " + _state + ", trying to port players back: " + e.getMessage(), e);
_state = GameState.GAME_STOPPED;
ThreadPoolManager.getInstance().scheduleGeneral(this, 1000);
ThreadPoolManager.schedule(this, 1000);
}
}
@@ -147,7 +147,7 @@ public class PunishmentTask implements Runnable
onStart();
if (_expirationTime > 0) // Has expiration?
{
_task = ThreadPoolManager.getInstance().scheduleGeneral(this, (_expirationTime - System.currentTimeMillis()));
_task = ThreadPoolManager.schedule(this, (_expirationTime - System.currentTimeMillis()));
}
}
@@ -91,7 +91,7 @@ public class LongTimeEvent extends Quest
else if (_eventPeriod.getStartDate().after(new Date()))
{
final long delay = _eventPeriod.getStartDate().getTime() - System.currentTimeMillis();
ThreadPoolManager.getInstance().scheduleGeneral(new ScheduleStart(), delay);
ThreadPoolManager.schedule(new ScheduleStart(), delay);
_log.info("Event " + _eventName + " will be started at " + _eventPeriod.getEndDate());
}
else
@@ -301,7 +301,7 @@ public class LongTimeEvent extends Quest
AnnouncementsTable.getInstance().addAnnouncement(new EventAnnouncement(_eventPeriod, _onEnterMsg));
// Schedule event end (now only for message sending)
ThreadPoolManager.getInstance().scheduleGeneral(new ScheduleEnd(), millisToEventEnd);
ThreadPoolManager.schedule(new ScheduleEnd(), millisToEventEnd);
}
/**
@@ -68,7 +68,7 @@ public class QuestTimer
_player = player;
_npc = npc;
_isRepeating = repeating;
_schedular = repeating ? ThreadPoolManager.getInstance().scheduleGeneralAtFixedRate(new ScheduleTimerTask(), time, time) : ThreadPoolManager.getInstance().scheduleGeneral(new ScheduleTimerTask(), time);
_schedular = repeating ? ThreadPoolManager.scheduleAtFixedRate(new ScheduleTimerTask(), time, time) : ThreadPoolManager.schedule(new ScheduleTimerTask(), time);
}
public QuestTimer(Quest quest, String name, long time, L2Npc npc, L2PcInstance player)
@@ -65,7 +65,7 @@ public class ResidenceFunction
final ResidenceFunctionTemplate template = getTemplate();
if ((template != null) && (_expiration > System.currentTimeMillis()))
{
_task = ThreadPoolManager.getInstance().scheduleGeneral(this::onFunctionExpiration, _expiration - System.currentTimeMillis());
_task = ThreadPoolManager.schedule(this::onFunctionExpiration, _expiration - System.currentTimeMillis());
}
}

Some files were not shown because too many files have changed in this diff Show More