Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
69 views
in Technique[技术] by (71.8m points)

java - Thread is stopped when I close my application

I have a question: my standalone java application runs a thread, this thread needs to sleep for 30 minutes then it runs some lines of code e.g. update the DB.

But when I close my application the thread is killed I presume because there is no update on the DB than 30 minutes.

So, how can I maintain the thread alive when I close the main thread?

Another question: if I kill the sub-thread from the Tasks Manager my application logic is corrupted. Therefore I need to change the logic I mean. Which is a possible solution for resolve this problem?

question from:https://stackoverflow.com/questions/65894265/thread-is-stopped-when-i-close-my-application

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you System.exit() your application or if your machine or operating system crashes or is turned off, there is not a good way to avoid pending work to be aborted.

The best thing you can do is to record the fact that something needs to be done persistently and check for it periodically.

If you wonder specifically about thread termination, the idea is that a Java runtime terminates itself as soon as there is no non-daemon thread left. So if you make your sleep thread not a daemon, it will stop the VM from ending itself. However this mechanism is rather dubious as you can't control very well when it will end.

If this is a GUI application, you will have to check yourself if it has pending work and deny the shutdown request before calling System.exit.

Just to mention it for completeness, there are also shutdown hooks, but it’s not a good idea to do heavy lifting in them, since they can't delay shutdowns indefinitely.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...