开发者

Java while loop in threads

I have written a program in Java which has 5 threads. In the run() I have a while loop which will loop over and over and this loop will loop a lot of times.

While the program is running, it is gradually eating ram bringing the program to a crawl. Is there anyway I can stop it eating all my ram?

Edit:

Actually just thinking about it, it probably is because the loop is creating lots of objects. Should I = null those objects a开发者_如何转开发t the end of the while loop??


If you are creating new objects and saving them in some collection in your loop that would easily fill up memory very quickly.

What you need to do is make sure you aren't saving any extra objects that you don't need.

Also, you should optimize the logic in your threads to consume the least amount of memory.


While the program is running, it is gradually eating ram bringing the program to a crawl. Is there anyway I can stop it eating all my ram?

Sure. Change your code so that it uses less RAM.


Specific to @Michael Borgwardt's answer, try to minimize the creation of new objects. If you can re-use the same object instead of creating new ones every time, you can save some memory there.

But as others have said, without seeing your code, we're just guessing.


You might need a memory analyzer to understand what is "eating RAM". There are many tools available. One commercial tool is JProfiler.

A simple and free tool is to use Sun Profiler supplied with Java VisualVM. If you have JDK 6 installed you probably already have this program installed on your computer. Run the C:\Program Files\Java\jdk1.6.0_16\bin\jvisualvm.exe. Connect to the running Java process and press the Profiler tab and Memory button. You can now see what objects you have and how much memory they are using. Press refresh to update the view.


It's normal for each one of your thread to have an infinite while loop, but simply having the while loops does not use up more RAM.

new Thread(new Runnable() {
    public void run() {
        try {
            while (true) {
                // do some work
            }
        } catch(InterruptedException ex) {}
    }
}).start();

You're doing something to consume the RAM, so you must debug your application and find the cause of the increased RAM usage.

Update:

You don't have to make the objects null at the end of the loop... if you're not holding on to a reference of those objects then the garbage collector should clean them up. What are you doing with the objects after you create them? How much RAM are you using up?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜