Improving Server Stability

Joined
Aug 2, 2010
Messages
190
Reaction score
91
For those people who are interested in improving their server stability, this thread is right for you. First of all, NEXON's main servers can support 1200 players on 4 GB of RAM and runs on Quad Core (Per Channel). Obviously, our OdinMS servers can't do that. However there is hope in obtaining this form of stability. Most of us here know LightPepsi and Celino. His server has supported 600+ players using only 2.2 GB of RAM. One conclusion that can be drawn from this is that server stability is not impossible. Most importantly, the way we code affects server stability.

Some ideas for improving server stability:
Object creation and fixing memory leaks.
Danger of finalizers.
Please contribute helpful ideas and opinions on your take towards a stabler server.
 
Last edited:
I don't think so. According to GoldenKevin's findings on KDev, it is 2 channels per server. The 'other' servers are probably isolated, e.g. database server, for better resource management. I would also like to know where you obtained your statistics from, stating a mere 'Quad Core' does not mean anything. Bear in mind there is the Intel C2Q series, Xeon, AMD Phenom Quad series, etc, that posses 4 cores.

NEXON actually does host 2 channels on one server. They do that with Channel 1 and 20. Since 20 is always the smallest populated channel, they host it along on channel 1 to save some resources.
 
Upvote 0
If you have a ResultSet and you are asking for the same row more than once or twice, store the value in a variable...

...instead of
Code:
if (rs.next()) {
Fag fag1 = new Fag(rs.getString("name"));
Fag fag2 = new Fag(rs.getString("name"));
Fag fag2 = new Fag(rs.getString("name"));
}
do
Code:
if (rs.next()) {
String fag = rs.getString("name");
Fag fag1 = new Fag(fag);
Fag fag2 = new Fag(fag);
Fag fag3 = new Fag(fag);
}



This as far as I know makes no difference. At least David told me so.

it looks cleaner, doesn't have to make a difference. Every coders' goal is to make their code shortened, but processed the same way. :P:
 
Upvote 0
Yes, they removed channel 20 for the purpose of reducing lag on channel 1
Though it didn't really fix anything, having more than 1000-1200 players on at once on channel 1 still crashes the channel, I remember this being done a while ago to cause rollback and duping

GMS needs checks... Don't allow more people if there are x amount of people in the channel..
 
Upvote 0
2. For objects that you do not intend to change, make them constant by adding the final keyword.

Won't do much, especially if it's on a method or class, then it's completely useless. Example public final class wejvlskdr {} is useless since unless that has classes overriding it (which here is impossible), java will automatically make it final. The same goes for methods.

Using final for variables is sometimes useless such as in local variables.
 
Upvote 0
Yes, they removed channel 20 for the purpose of reducing lag on channel 1
Though it didn't really fix anything, having more than 1000-1200 players on at once on channel 1 still crashes the channel, I remember this being done a while ago to cause rollback and duping

I see.. that's why crashes that will cause massive rollback only occur during 2x EXP event. They must have ran out of memory or something? :D
 
Last edited:
Upvote 0

Suggestion: MapleMap.java
PHP:
private final Map<MapleMapObjectType, LinkedHashMap<Integer, MapleMapObject>> mapobjects = new EnumMap<MapleMapObjectType, LinkedHashMap<Integer, MapleMapObject>>(MapleMapObjectType.class);
See if you can figure out why...


Also, if you plan to only run your server on one machine --> Get rid of RMI, combine everything into 1 JVM.
 
Last edited:
Upvote 0
Don't declare variables within for statements. For example, this is wrong:

Code:
for (int i = 0; i < 5; i++) {
     int a = 0;
     a = mob.getHp();
}


Instead, you would want to do:

Code:
int a;
for (int i = 0; i < 5; i++) {
     a = mob.getHp();
}


This makes no difference in terms of performance. The JVM is a stack based machine, and local variables such as "a" you defined up there are pushed onto the stack and popped off the stack, not in the heap. Here's a bit of pseudocode so you can understand it:

If I had a piece of code like so:

Code:
int a = 1 + b;

the resulting bytecode will look something like

Code:
push b
push 1
add
stor a

as you can see, the JVM is using the stack to store the local variable, not the heap. The heap is used to store Objects, Arrays and other things, not primitives.

Also..

Code:
Object z;
for (...) {
 z = new Object();
}

is not faster than

Code:
for (...) {
 Object z = new Object();
}

Anyway, you are looking at micro-optimizing here, which is useless in terms of server stability, what the hell is gaining one extra clock cycle per function that is called once every hour going to help in terms of server stability?

To optimize, I'll outline the key aspects of maintaining a stable server program:

RMI - RMI is synchronized, causing threads to block while they wait for a response from a remote server. Blocking means the thread will stop executing further instructions until notified it can again. Now, imagine this scenario: For some reason, all 20 of your MINA threads are blocked by RMI. What will happen? Obviously, a bit of lag, because the MINA threads are unavailable to process the incoming requests. Using an asynchronous approach would be a better idea. RMI also uses insane amounts of bandwidth compared to what it *could* use, due to using ObjectInputStream and ObjectOutputStream.

MySQL Database - The MySQL database connector uses a singleton connection, which could be optimized to use a connection pool. For example, you could initialize the pool with 5 MySQL connections and make a connection manager class. This means that there is no waiting for a connection to connect to the database before you can use it, greatly speeding up MySQL transactions. This is especially important if your MySQL server is offloaded.

The Heap - Massive amounts of objects are created and destroyed every program loop. The garbage collector is very good at finding "dead" objects and deallocating the memory they possess. In fact, a memory allocation in Java could possibly be a lot faster than a memory allocation in C/C++ due to the JVM's memory manager knowing which parts of heap memory are empty and directly using that address. However, when too many objects are created and destroyed every loop, the garbage collector has more work to do, and therefore will take longer to complete its collection. This in turn will slow down your server.

Resource leaks - Multiple handles are opened by the server during its lifetime. From what i've seen, many of these handles are not closed, creating resource leaks. A resource leak is similar to a memory leak in that if it keeps leaking eventually you will run out of resources. Make sure you always close() the statement/file/whatever after using, in a finally block.

Memory leaks - Memory leaks happen when memory referenced by an object is not freed when it should, usually due to another object retaining a strong reference to the object that should be garbage collected. In order to fix these, use the classes SoftReference, WeakReference and PhantomReference. To track what objects have been queued by the garbage collector, you can use a class named ReferenceQueue.

- David

---------- Post added at 09:18 AM ---------- Previous post was at 09:09 AM ----------

It doesn't only look cleaner, it also processes faster because ResultSets don't cache. (Another thing David taught me).

The default MySQL implementation does not cache, however it is possible to make it cache

Also..

6.1.21 Closing a ResultSet Object

Normally, nothing needs to be done to close a ResultSet object; it is automatically closed by the Statement object that generated it when that Statement object is closed, is re-executed, or is used to retrieve the next result from a sequence of multiple results. The method close is provided so that a ResultSet object can be closed explicitly, thereby immediately releasing the resources held by the ResultSet object. This could be necessary when several statements are being used and the automatic close does not occur soon enough to prevent database resource conflicts.
 
Last edited:
Upvote 0

Suggestion: MapleMap.java
PHP:
private final Map<MapleMapObjectType, LinkedHashMap<Integer, MapleMapObject>> mapobjects = new EnumMap<MapleMapObjectType, LinkedHashMap<Integer, MapleMapObject>>(MapleMapObjectType.class);
See if you can figure out why...


Also, if you plan to only run your server on one machine --> Get rid of RMI, combine everything into 1 JVM.

HashMap <> Integer searching via .get, set doesn't makes any difference, the only thing I can think of is the improved speed of getting certain map objects such as reactors. Great idea though, since it's used very often!
 
Last edited:
Upvote 0
Using final for variables is sometimes useless such as in local variables.
Hotspot isn't terribly great in figuring out what's final and what's not, it's a good idea to hint it a little. However this will not bring lots of speed gains it mostly helps readers of your code.

MySQL Database - The MySQL database connector uses a singleton connection, which could be optimized to use a connection pool. For example, you could initialize the pool with 5 MySQL connections and make a connection manager class. This means that there is no waiting for a connection to connect to the database before you can use it, greatly speeding up MySQL transactions. This is especially important if your MySQL server is offloaded.
Actually there are ThreadLocal connections so one connection per Thread accessing the database. More would not make sense. Sometimes less connections might be useful but it's hard to figure out the right amount as opening and closing connections is quite expensive. However do note that accessing the Database is quite slow as it involves network access.
I agree to everything else you said. However do be careful when optimizing away Object creation as you can easily make your code less readable.


Also: It is an incredibly bad idea to use non int or long types for numbers that you calculate with. Hotspot can't work with such values at all (converts them to int). In short: Using "short" and "byte" datatypes makes your program slower and rarely gains you anything.
 
Last edited:
Upvote 0
This makes no difference in terms of performance. The JVM is a stack based machine, and local variables such as "a" you defined up there are pushed onto the stack and popped off the stack, not in the heap. Here's a bit of pseudocode so you can understand it:

If I had a piece of code like so:

Code:
int a = 1 + b;

the resulting bytecode will look something like

Code:
push b
push 1
add
stor a

as you can see, the JVM is using the stack to store the local variable, not the heap. The heap is used to store Objects, Arrays and other things, not primitives.

Also..

Code:
Object z;
for (...) {
 z = new Object();
}

is not faster than

Code:
for (...) {
 Object z = new Object();
}

Oh, I get it. I forgot who had told me that that the JVM would just keep making another additional 4 bytes, and not just add it in. Thanks for explaining that David, but could you please explain why having Object z within the for statement would be faster than having it outside of it, or is it for the same reason as the int?
 
Upvote 0
Regarding the inside/outside loop object initialization:

Java code:
Code:
public class Test1 {
    public static void main(String[] args) {
        Object z;
        for (int i = 0;i < 5;i++) {
             z = new Object();
        }
    }
}
Disassembled Bytecode:
Code:
Compiled from "Test1.java"
public class Test1 extends java.lang.Object{
public Test1();
  Code:
   0:   aload_0
   1:   invokespecial   #1; //Method java/lang/Object."<init>":()V
   4:   return

public static void main(java.lang.String[]);
  Code:
   0:   iconst_0
   1:   istore_2
   2:   iload_2
   3:   iconst_5
   4:   if_icmpge       21
   7:   new     #2; //class java/lang/Object
   10:  dup
   11:  invokespecial   #1; //Method java/lang/Object."<init>":()V
   14:  astore_1
   15:  iinc    2, 1
   18:  goto    2
   21:  return

}


Java Code:
Code:
public class Test2 {
    public static void main(String[] args) {
        for (int i = 0;i < 5;i++) {
             Object z = new Object();
        }
    }
}
Disassembled Bytecode:
Code:
Compiled from "Test2.java"
public class Test2 extends java.lang.Object{
public Test2();
  Code:
   0:   aload_0
   1:   invokespecial   #1; //Method java/lang/Object."<init>":()V
   4:   return

public static void main(java.lang.String[]);
  Code:
   0:   iconst_0
   1:   istore_1
   2:   iload_1
   3:   iconst_5
   4:   if_icmpge       21
   7:   new     #2; //class java/lang/Object
   10:  dup
   11:  invokespecial   #1; //Method java/lang/Object."<init>":()V
   14:  astore_2
   15:  iinc    1, 1
   18:  goto    2
   21:  return

}

You can see it's virtually identical.

You should generally declare variables to have the minimum scope necessary to achieve your goals (or at least that's how I like to do it...), so your usage will depend.


Edit:
Also: It is an incredibly bad idea to use non int or long types for numbers that you calculate with. Hotspot can't work with such values at all (converts them to int). In short: Using "short" and "byte" datatypes makes your program slower and rarely gains you anything.

In regards to this ... no way... your program would not slow down significantly... the cost is minor. What you gain is more free memory, an important part of increasing server capacity. By your logic, we should take ByteArrayMaplePacket and turn it into an IntegerArrayMaplePacket ... Lol?
 
Last edited:
Upvote 0
In regards to this ... no way... your program would not slow down significantly... the cost is minor. What you gain is more free memory, an important part of increasing server capacity. By your logic, we should take ByteArrayMaplePacket and turn it into an IntegerArrayMaplePacket ... Lol?[/COLOR]

Actually operations with byte/short are about 3 times as expensive as operations with int. I wouldn't call this cost minor. This of course only applies if you do anything with the values. Comparison and Arithmetics are expensive, just having it around is free of course. As a rule of thumb: If you do any caluclations or comparisons with the value try to have it as int...
Example: The level of a character changes relatively seldomly so we could keep it as byte instead of int. If there are any minlevel checks for equip however it's probably a bad idea. (Aside from having the character level as byte isn't worth it)

But always keep in mind the first rule of software optimization: Don't do it!
And the second rule: If you REALLY have to: use a profiler to find out where your program is spending time and reduce the hotspots (80/20 rule, etc.). Same is true for memory, analyze a heap and see where you can save memory instead of using primitives somewhere, you can probably easily find a whole bunch of objects that you could throw away. For example Odin NEVER unloads data of items, maps and skills and keeps quite a bit of data duplicated in memory. This follows the design principle that memory is cheap. If you want to save memory introduce expiring caches.
 
Upvote 0
Actually operations with byte/short are about 3 times as expensive as operations with int. I wouldn't call this cost minor. This of course only applies if you do anything with the values. Comparison and Arithmetics are expensive, just having it around is free of course. As a rule of thumb: If you do any caluclations or comparisons with the value try to have it as int...
Example: The level of a character changes relatively seldomly so we could keep it as byte instead of int. If there are any minlevel checks for equip however it's probably a bad idea. (Aside from having the character level as byte isn't worth it)

But always keep in mind the first rule of software optimization: Don't do it!
And the second rule: If you REALLY have to: use a profiler to find out where your program is spending time and reduce the hotspots (80/20 rule, etc.). Same is true for memory, analyze a heap and see where you can save memory instead of using primitives somewhere, you can probably easily find a whole bunch of objects that you could throw away. For example Odin NEVER unloads data of items, maps and skills and keeps quite a bit of data duplicated in memory. This follows the design principle that memory is cheap. If you want to save memory introduce expiring caches.


I'd like to know where you are getting "3x" from. Even if this is the case, it is minor compared to other bottlenecks such as slow synchronization (which I think can be hundreds of times slower than if done properly, but I'll need to check) and deadlocks (in which anything else is a moot point, because your application is now doing nothing). Just a few days ago, I changed a ReentrantLock into a ReentrantReadWriteLock in a heavily used part of our source, and the function used up less than 1% of the total JVM CPU time instead of the original 20-30%.

The heaviest computational operations are the encryption and decryption of packets (Just take a look at the encryption and decryption routines =P)... so we should convert ByteArrayMaplePackets into IntegerArrayMaplePackets if your reasoning is correct. In comparison, the other computations done on the server form just a small volume of the total.

Additionally, memory in Java is not quite as cheap as it is in other languages, it takes a significant effort for the GC to reclaim unused memory.

Also, this entire thread is about changes or optimizations that could improve server stability, I think we should assume that anyone interested has already done the necessary cost/benefit analysis that comes with optimization, but yes, you are correct. Premature optimization is never a good idea.

Finally, yes I agree, if you want to optimize properly, use a memory or CPU profiler to figure out where most of your resources are going towards.
 
Last edited:
Upvote 0

I'd like to know where you are getting "3x" from.

Personal microbenchmarks. Which may not be entirely correct. Combined with the fact that sun documents say that hotspot can not do byte and short arithmetics, it upcasts to ints, does stuff then downcasts again.


Intresting ideas about the encryption. It might just be a win. The problem here is of course that that would increase memory usage a lot (probably) and more importantly copying the data back to a byte buffer becomes more expensive. Also the encryption logic specially relies on byte behaviour (overflows, bit shifting, bit rolling) you'd have to emulate this thereby slowing things down again.
I don't really think that we could really gain performance here unless someone can convert most of the logic to REALLY use integer arithmetic (doing 4 bytes at once). This might be hard as I'm unsure if there's anyone around who understands what that code is really doing and why. However it would be an intresting experiment.

Even if this is the case, it is minor compared to other bottlenecks such as slow synchronization (which I think can be hundreds of times slower than if done properly, but I'll need to check) and deadlocks (in which anything else is a moot point, because your application is now doing nothing). Just a few days ago, I changed a ReentrantLock into a ReentrantReadWriteLock in a heavily used part of our source, and the function used up less than 1% of the total JVM CPU time instead of the original 20-30%.
Yes of course. Thread stalling/lock contention means you are wasting good cpu cycles waiting for something. That's worse most of the time.

Anyway my original point is: It's probably not worth it memorywise to change ints to short (saving 2megabyte for each 1 million of these, whoo - a single object instance usually takes ~16 byte - depending on vm used) if you want to save memory you should look into other ways first as changing ints to short probably gains you little memory and makes you jeopardize performance.
 
Last edited:
Upvote 0
Hotspot isn't terribly great in figuring out what's final and what's not, it's a good idea to hint it a little. However this will not bring lots of speed gains it mostly helps readers of your code.


Actually there are ThreadLocal connections so one connection per Thread accessing the database. More would not make sense. Sometimes less connections might be useful but it's hard to figure out the right amount as opening and closing connections is quite expensive. However do note that accessing the Database is quite slow as it involves network access.
I agree to everything else you said. However do be careful when optimizing away Object creation as you can easily make your code less readable.


Also: It is an incredibly bad idea to use non int or long types for numbers that you calculate with. Hotspot can't work with such values at all (converts them to int). In short: Using "short" and "byte" datatypes makes your program slower and rarely gains you anything.

I did not mean keep using one per thread, instead make about five to start off with, make a manager class that you can fetch and repool from, when another one is required but does not exist, you can open a new connection. Make them time out after, say 5 minutes of inactivity. Also, using this kind of design architecture will use less connections.

- David

---------- Post added at 03:49 AM ---------- Previous post was at 03:33 AM ----------

<snip>
Anyway my original point is: It's probably not worth it memorywise to change ints to short (saving 2megabyte for each 1 million of these, whoo - a single object instance usually takes ~16 byte - depending on vm used) if you want to save memory you should look into other ways first as changing ints to short probably gains you little memory and makes you jeopardize performance.

most people have 8gb ram dedis these days, what will saving 2mb per 1mil objects save you? I don't even see how memory can be a problem..

- David
 
Upvote 0
most people have 8gb ram dedis these days, what will saving 2mb per 1mil objects save you?
That's what I was trying to say

I don't even see how memory can be a problem..
When you reach above 2500 concurrent users you will notice that 8gb are running short. But once again: Fixing this can/should not be accomplished by using smaller primitive types.
 
Upvote 0
Back