How to change Thread implementation to use ExecutorService

I was making a game and using Threads in my program to complete tasks. So let me explain the scenario a bit. I have a BattleManager class that implements Runnable and continues to loop in the battle queue, if any.

@Override
    public void run() {
        while(serverRunning){
            synchronized (battleQueue) {
                for(Battle battle : battleQueue){
                    if(battle != null){
                        if (battle instanceof WildBattle) {
                            if(!((WildBattle) battle).isBattleOver()){
                                ((WildBattle) battle).tryExecuteBattleTurn();
                            }else{
                                battleQueue.remove(battle);
                                battle = null;
                            }
                        }
                    }
                }
            }
            try {
                Thread.sleep(3);
            } catch (InterruptedException e)
                e.printStackTrace();
            }
        }
        currentThread = null;
    }

      

Then I check if the battle is over, and if not, I try to complete the battle. Since there can be more than 100 battles in each battle, and there are complex calculations in each battle, I create a child thread inside the WildBattle class to perform the task so that the battles run in parallel.

Here is a method called inside the wild battle class that generates a new stream.

 public void tryExecuteBattleTurn() {
        if (!isBattleTurnRunning && battleThread == null) {

            battleThread = new Thread(new Runnable() {
                @Override
                public void run() {
                    //long startTime = System.currentTimeMillis();
                    executeBattle();
                    battleLog.setBattleLog("");
                    battleThread = null;
                    //System.err.println("Total execution time : " +(System.currentTimeMillis() - startTime));
                }
            }, "Battle thread");

            battleThread.start();
        }
    }  

      

Now for the main question, I want to learn about the executor service, and I've read in several places that it is always better to use the executor service rather than creating new child threads. How can I change this to use the executor service. I'm not sure though. I am not a Java expert and am still learning the language, so spare me if you see something is wrong and please let me know if I can change anything to make it more efficient. Let me know if you don't know anything.

+3


source to share


1 answer


I'll show you a basic example and you will understand how to integrate it with your code.

First you create ExecutorService

somewhere in your application.

ExecutorService executorService = Executors.newFixedThreadPool(NUMBER_OF_THREADS);

      

You have to choose the NUMBER_OF_THREADS

application based on your needs. Themes are not created immediately - only when a task is sent for maintenance and there are no threads available for it. If everyone is NUMBER_OF_THREADS

busy, the task will wait in the queue until one of the threads can process it. ExecutorService

will reuse streams, it will save time on stream creation and would be a generally good concept for working with streams.



You then control access to the executor service from your battles. Then, when you need to do asynchronous work, you submit the task to service:

executorService.submit(new Runnable() {
    @Override public void run() {
        // your code here
    }
}

      

If your application has a life cycle and can be shut down in some way, you also want to shut down ExecutorService

. There are two options: shutdown()

and shutdownNow()

, the first waits for all current tasks to be completed, the second exits immediately and returns a list of tasks that have not been completed.

As mentioned in the comments, you should figure out how to save the model state and arrange for thread synchronization based on your actual situation.

+1


source







All Articles