-2

Does creating more objects lead to more resource consumption in java?

DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                Date date = new Date();
                dateandtime.setText(dateFormat.format(date));
            }
        },0,1000);

I have this code and the application needs to run continuously for years. I am worried that with time resources used by the app may increase due to the creation of a new object every second.

1 Answers1

2

In theory: Yes. Every object you create does take up space.

However, Java uses this thing called a garbage collector. See this question

In short: It will take care of getting rid of objects that aren't referenced to anymore. So you don't have to worry about creating more and more objects in your piece of code.

Keep in mind that it IS in fact possible to create objects in a way that the garbage collector won't be able to clean up. So you can't just go ahead and think you never have to worry about things like this.

Your code however is not like that. You won't get a problem.

Mark
  • 1,498
  • 1
  • 9
  • 13