datetime - Memory leaking with Date and string java -


i'm using below code having time section in application. below code leaks memory gradually. because of settext() in jlabel?

can me identifying error?

also please let me know how release memory of dateformat , date in java.

    thread th= new thread(new runnable() {          public void run() {             dateformat dateformat_s2= null;             date date_int_s2=null;             string date_time_s2=null;             while(c==1) {                   try {                     thread.sleep(50);                  } catch (interruptedexception e) {                     e.printstacktrace();                 }                 dateformat_s2= new simpledateformat("dd:mm:yyyy  hh:mm:ss");                 date_int_s2= new date();                 date_time_s2 = dateformat_s2.format(date_int_s2);                 time_end_label.settext(""+date_time_s2);                 date_time_s2=null;                 dateformat_s2=null;                 date_int_s2=null;             }         }     }); 

to monitor memory usage need @ memory used after full gc. else miss leading have objects might cleaned have not yet.

note: there no need setting values null gc clean them go. using local variable inside loop discards object on every iteration.

note: can calculate how ling until next second can once per second instead of 20 times per second.

you re-write code this

public static void starttimer(jlabel time_end_label) {     thread th = new thread(new runnable() {          public void run() {             dateformat dateformat_s2 = new simpledateformat("dd:mm:yyyy  hh:mm:ss");             while(!thread.currentthread().isinterrupted()) {                 date date = new date();                 final string date_time = dateformat_s2.format(date);                 swingutilities.invokelater(new runnable() {                     @override                     public void run() {                         time_end_label.settext(date_time);                     }                 });                 long delay = 1000 - date.gettime() % 1000;                 try {                     thread.sleep(delay);                 } catch (interruptedexception e) {                     break;                 }              }         }     });     th.setdaemon(true);     th.start(); } 

however simpler use swing timer actionlistener executed in gui event loop thread you.

public static void starttimer(jlabel time_end_label) {     dateformat dateformat= new simpledateformat("dd:mm:yyyy  hh:mm:ss");     final actionlistener listener = new actionlistener() {         @override         public void actionperformed(actionevent e) {             date date = new date();             final string date_time = dateformat.format(date);             time_end_label.settext(date_time);             int delay = (int) (1000 - date.gettime() % 1000);             new timer(delay, this).start();         }     };     new timer(1, listener).start(); } 

Comments