Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javax.swing.Timer vs java.util.Timer

Tags:

java

I heard all javax.swing classes should only be used if Iam actually building a Swing GUI. I would like to use javax.swing.Timer without GUI in order to create timer loop. Does it mean that without GUI shall i use java.util.Timer?

Is it big error to use javax.swing.Timer without GUI ? Can it cause some performance error or slowdown?

What are some approaches to creating a loop that will run passively or without halting the main thread?

Thanks in Advance!

like image 360
DRastislav Avatar asked May 08 '13 17:05

DRastislav


1 Answers

Is it big error to use javax.swing.Timer without GUI ? Can it cause some performance error or slowdown?

No, It is not a big error. But , the ActionEvents associated with the javax.swing.Timer won't fire if there is no non-daemon thread running in the application . If no non-daemon thread is running in application then the program will exit gracefully without making the javax.swing.Timer to execute associated actionPerformed method. But GUI causes the JVM to hang up and let the Timer to execute the actionPerformed method.
In case you are not using GUI, make sure that there is some non-daemon thread running in application.

What are some approaches to creating a loop that will run passively or without halting the main thread?

You can use java.util.Timer for this purpose. But now java.util.concurrent has provided a lot of enrich set of APIs to perform concurrent tasks. So , now you should move on to ScheduledExecutorService API for this purpose.

like image 194
Vishal K Avatar answered Sep 27 '22 22:09

Vishal K