Pages

Wednesday, February 14, 2007

Java Thread Stack performance

The question came up at work the other day on how to solve problems with threads ‘losing’ resources. In particular, I think that threads aren’t release holds on database connections (bad). Basically at some point we run out of connections to use and everything goes to hell.

So, since we have access to the thread objects, I thought that it might be worth while finding where these threads are up to.
Strike 1.
Only Java 1.5 has Thread.getStackTrace(). We are running in 1.4

Well, what would be the performance of doing such a thing anyway.

One way of getting the stack is:
[java]try
{
throw new RuntimeException();
} catch(RuntimeException re)
{
result = re.getStackTrace()[0].getMethodName();
}

Java 1.4 via throw and catch method:
Execution length:1376
Execution length:1258
Execution length:1278
Execution length:1295
Execution length:1285

Java 1.5 via same method:
Execution length:1295
Execution length:1233
Execution length:1238
Execution length:1252
Execution length:1229

Good start: There is little difference between using 14 or 15.

But use:
[java]Thread.currentThread().getStackTrace()[0].getMethodName()
Java 1.5 via Thread.getStackTrace()
Execution length:15938
Execution length:16308
Execution length:12004
Execution length:16804
Execution length:17009

Definitely room for improvement.

Each of the stack elements was queried 100,000 times.
This test was done 5 times end to end.

This test does not answer a tougher question like "if the stack trace is deeper, would it become slower?".
The slower method is the only way (I know of) to access the stack of a thread that is not driving the current code though.

No comments:

Post a Comment