Destroying Date object

83 Views Asked by At

I need some advice on this code:

Thread myClock = new Thread() {
  @Override
  public void run() {
    try {
      while (!isInterrupted()) {
        Thread.sleep(1000);
        runOnUiThread(new Runnable() {
          @Override
          public void run() {
            Date dt = new Date();
            SimpleDateFormat myClockDate = new SimpleDateFormat("EEE, dd MMM yyyy");
            SimpleDateFormat myClockTime = new SimpleDateFormat("hh:mm aa");
            myClock_date.setText("Date:  " + myClockDate.format(dt));
            myClock_time.setText("Time:  " + (myClockTime.format(dt)).replace(".", ""));
          }
        });
      }
    } catch (InterruptedException e) {

    }
  }
};

It works well but when the thread is running, the memory monitor shows a consistent rise and fall in usage. When it's not running, the monitor flat-lines.

I'm wondering if it's the continuous creation of the date object that's causing this? Does it need to be destroyed or released?

PS: The GPU monitor has been disabled.

1

There are 1 best solutions below

2
On

Every second your code creates a Runnable, a Date, and two DateFormat objects. Also the string operations may create some objects. Once the Runnable finishes those get cut loose (nothing outside the Runnable has a reference to any of them) and are eligible for garbage collection. You don't need to do anything further to release their memory. you should see memory usage return to the same level after each of these Runnables completes.

Garbage collection is not immediate. As long as you don't see an ongoing upward trend it's ok.