Reputation: 133
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
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
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
Reputation: 5858
There are two ways I can think of off the top of my head.
Instead of only 1 client per thread. Try having a collection of X clients per thread. Then loop through the clients moving each one.
Use a JMeter or other distributed testing suite to spread threads across multiple computers.
Upvotes: 1