user381878
user381878

Reputation: 1539

how to control Daemon thread?

I am writing a Java application in which i m writing a thread program to read a file. Every time the program is run it will create a thread and read the file. Its time consuming, I know the file will never change so I want to make a daemon thread which will read the file only once and store it in a String.

The am facing several problems- 1) Once i start the daemon thread, How do i access it again? 2)If I want to stop the daemon thread, how do i do it?

Please help.

thanks,

Upvotes: 1

Views: 678

Answers (3)

G__
G__

Reputation: 7111

If you want to access your thread, just keep a reference to the Thread object. Likewise, if you want to access your string keep a reference to the String object. These references could be stored as static variables, but they don't have to be.

Stopping a thread directly via Thread.stop() or Thread.suspend() is deprecated. See this article for a description of why, and a "proper" way to stop threads.

Upvotes: 0

sasuke
sasuke

Reputation: 6759

I think you are confused with the way a daemon thread works. A daemon thread doesn't prevent the application from quitting if it's the only thread running; user threads do. If you know the file is never going to change, why not load it once without using any thread? Also, after the file loading is done by your daemon thread (i.e. the run() method completes normally), it'll automatically be handled by your runtime unless you've got an infinite loop in your run() method. IMO posting a bit of code would help the cause here.

Upvotes: 2

Andreas Dolk
Andreas Dolk

Reputation: 114837

I guess, your daemon will live in a different virtual machine, and in this case, you can't access the String from your application.

Upvotes: 1

Related Questions