Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running an infinite java program and how performance is affected

So im not much of a thread expert, nor java for that matter.

Okay so I made a little program that runs infinite.. (its supposed to)

Get data from XML file every minute and prints it. The xml updates every couple of seconds, but only want the 1 minute print. So my main looks something like this.

while(true) {
   try {
       Thread.sleep(60000);
       String data = getSomeDataFromXMLFile();
       System.out.println(data);
   } catch (InterruptedException e) {
       e.printStackTrace();
   }

The code works how its supposed to. Just wanting to know if it can affect my servers performance in any way? Like after 10 days of running it hogs all RAM or something..

Suggestions and improvements are very welcome.

like image 540
Rayf Avatar asked Dec 06 '22 10:12

Rayf


1 Answers

Assuming that getSomeDataFromXMLFile() is correct (does not leak memory), your code is fine. Maybe not beautiful, but fine.

One small unrelated improvement - if you want to read a file every minute (as opposed to: sleep for a minute between each read) you'll have to take the time of getSomeDataFromXMLFile() into account.

Consider Timer class to shrink your code a bit and avoid the problem above:

Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
    @Override
    public void run() {
        String data = getSomeDataFromXMLFile();
        System.out.println(data);
    }
}, 0, 60000);
like image 142
Tomasz Nurkiewicz Avatar answered Feb 20 '23 00:02

Tomasz Nurkiewicz