5

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!

2 Answers 2

9

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Well, i have java 1.7.0 and i use javax.swing.Timer in application with no GUI whatsoever, and it works perfectly, just add java.awt.event.ActionListener and its k.
@kajacx: Yeah you are right in your words that there is no error if javax.swing.Timer is used to with non-GUI application. There is absolutely no Error in doing this. But what I wanted to emphasize that the ActionEvent related to javax.swing.Timer wouldn't fire if there is no non-daemon thread running in application. And GUI causes the JVM to hang up till all the GUIs are not disposed.
Yea, that daemon thing is pretty annoying
1

Yes it is not recommended since it is another dependency you need.

You should try to have as few as possible dependencies. If java.util.Timer is something that satisfies your needs you definitely should choose this one.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.