Robert Stevens
Robert Stevens

Reputation: 528

java from a program that runs 1000 times in a row to muli threading

i am still new to java in run this code arround 1000 time in a row now so its probably mutch more efficent to run it multithread but i have no idea what the best idea is to give the score back to the main thread

    private int StartGameRandom(EntityManager managerOrg, UserInput input)
{
    EntityManager manager = managerOrg.cloneState(managerOrg);
    int playerId = 0;
    int score = 0;

    //get the player id from the player that has to play
    ArrayList<Entity> tempState = manager.getAllWithComponents(PhaseComponent.class);
    if (tempState.isEmpty())
        System.err.println("ScoreSystem.addScorePlayer noPlayerComponent found");
    Entity state = tempState.get(0);
    PhaseComponent sComponent = (PhaseComponent) state.getComponent(PhaseComponent.class);
    playerId = sComponent.getPlayerId();

    SetPlayersToRandom(manager);
    new PhaseSystem(manager, input);

    ArrayList<Entity> tempPlayer = manager.getAllWithComponents(PlayerComponent.class);
    if (tempPlayer.isEmpty())
        System.err.println("montecarlo.startgamerandom noPlayerComponent found");
    Entity[] players = new Entity[tempPlayer.size()];
    tempPlayer.toArray(players);

    //set all the players to random ai
    for (Entity entity : players) {
        PlayerComponent component = (PlayerComponent) entity.getComponent(PlayerComponent.class);
        if (component.getPlayerID() == (byte)playerId)
        {
            score = component.getTotalScore();
            break;
        }
    }

    return score;
}

this is what i do with the scores

                    for (int j = 0; j < RUNS; j++ )
                {
                    int score = StartGameRandom(manager,input);
                    maxScore = Math.max(score, maxScore);
                    if (j == 0)
                    {
                        minScore = score;
                        averageScore  = score;
                    }
                    else
                    {
                        minScore = Math.min(score, minScore);

                        averageScore  = ((averageScore*j)+score)/(j+1);
                    }
                }

so what is the best way to do this in java

Upvotes: 0

Views: 188

Answers (1)

Enno Shioji
Enno Shioji

Reputation: 26882

Making stuff multithreaded doesn't automatically make things faster. Indeed, multithreading shouldn't be your first option for optimization.

I'm not entirely sure what your code does, but from the fact that it's taking 10 minutes and an EntityManager is involved, I'm guessing that the DB calls are the culprit.

You should investigate how much time you are spending on each part and see if your DB queries are inefficient, or if you are making lots of separate calls (that you could merge into fewer calls).

Upvotes: 2

Related Questions