About command parallelism... #2391
-
First of all, I'm sorry I'm a beginner about JDA and git. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
There are a lot of things you can do to solve this problem, most importantly you should look into reducing how long your commands take.
If you have a lot of CPU computations, for example due to image processing, then you will have to use a thread-pool instead. Note, however, that you are still limited by how much your CPU can handle at a time. To use a thread-pool, make a globally accessible (e.g. static) field that you can re-use everywhere. This allows you to avoid leaking resources by creating excessive threads everywhere. There are multiple types of pools you can use, but you most likely want a fixed size pool, unless you do some kind of heavy I/O bound tasks.
Here is an example use: public class Globals {
public static final int NUM_CORES = Runtime.getRuntime().availableProcessors();
// Create a thread-pool with 2 or CPU core number of threads
public static final ThreadPoolExecutor pool = Executors.newFixedThreadPool(Math.max(2, NUM_CORES));
} public class ImageCommand extends ListenerAdapter {
@Override
public void onSlashCommandInteraction(SlashCommandInteractionEvent event) {
// Reply before scheduling your task, just to be safe since it might take a moment for your task to run
event.deferReply().queue();
// Run your expensive task on a separate, but managed, thread
Globals.pool.execute(() -> {
Image someImage = getRandomImage();
someImage = crazyExpensiveComputation(someImage);
event.getHook().editOriginalAttachments(someImage.toInputStream()).queue();
});
}
} Note: This will also prevent your program from stopping if you call
|
Beta Was this translation helpful? Give feedback.
There are a lot of things you can do to solve this problem, most importantly you should look into reducing how long your commands take.
complete()
, instead rely only onqueue(...)
callbacksThread.sleep(...)
orFuture#get
If you have a lot of CPU computations, for example due to image processing, then you will have to use a thread-pool instead. Note, however, that you are still limited by how much your CPU can handle at a time.
To use a thread-pool, make a globally accessible (e.g. static) field that you can re-use everywhere. This allows you to avoid leaking resources by creating excessive threads everywhere.
There are multiple …