dlwells02
dlwells02

Reputation: 133

Java Threading - Alternative to spawning a huge amount of threads

I'm currently creating a simulation program to simulate clients moving around the map of a massively multiplayer online game. I have to have a grid to represent the map, which holds Client objects. These Clients must move around the grid randomly, each communicating with a Server object.

At the moment I start a new Thread for each Client, and it calls a method in its' server with a random direction of movement each second.

This works fine until I start adding a huge number of clients (~5000), where the program crashes and I get a "java.lang.OutOfMemoryError: unable to create new native thread" exception.

Is there an alternative way to deal with such a large amount of clients without them each being a separate thread?

Thanks, Dan

Upvotes: 0

Views: 424

Answers (3)

b_erb
b_erb

Reputation: 21251

Have you considered using the actor concurrency model for that? Akka provides a mature library-based actor implementation for that. It allows you to create huge amount of objects that can communicate with each other using message passing. It is backed by a threadpool.

http://akka.io/docs/akka/1.2/java/untyped-actors.html

Upvotes: 2

meriton
meriton

Reputation: 70574

Why on earth are you giving each client its own thread? Simply have one thread do the following:

for (;;) {
    for (Client c : clients) {
        c.update();
    }
    Thread.sleep(1000);
}

That has the advantage that fairness is guaranteed (all clients get updated, even if the system is overloaded), and the server need not be thread-safe. Moreover, a for-loop is far more efficient than switching threads, will consume less memory (each thread has a stack allocated).

Upvotes: 4

Daniel Moses
Daniel Moses

Reputation: 5858

There are two ways I can think of off the top of my head.

1 - Have each thread contain a collection of clients.

Instead of only 1 client per thread. Try having a collection of X clients per thread. Then loop through the clients moving each one.

2 - Truely distribute your clients

Use a JMeter or other distributed testing suite to spread threads across multiple computers.

Upvotes: 1

Related Questions