Java daemon threads read configuration files
For some applications, the configuration file needs to be read in real time, but the read frequency is very high. For example, if the configuration file is modified more than 100 times per second, the frequency of modification is much lower than the read frequency. In this case, when the program is executed
When reading the configuration file, the system's Io may be under some pressure. Therefore, you can use a daemon thread to read the configuration file at intervals (for example, 1 minute, the Code directly obtains the value of the latest configuration file.
This not only reduces the frequency of reading configuration files, but also achieves better real-time performance.
The Code is as follows: Java code
- Import
Java. Io. inputstream;
- Import
Java. util. properties;
- /**
- * System Configuration File
- * @ Author sunbin
- *
- */
- Public
Class
Configation
Extends
Thread {
- // Static Attribute Class
- Private
Static
Properties P;
- /**
- * Default constructor
- */
- Public
Configation (){
- //
- }
- /**
- * Inherit the methods that must be implemented by the thread
- */
- Public
Void
Run (){
- While
(
True
){
- // Obtain the configuration file in classpath
- Inputstream in = configation. Class
. Getclassloader (). getresourceasstream (
"Config. properties"
);
- If
(P =
Null
){
- P = new
Properties ();
- }
- Try
{
- P. Load (in );
- In. Close ();
- Thread. Sleep (10000
);
// Reread the configuration file after 10 seconds of sleep
- } Catch
(Exception e ){
- E. printstacktrace ();
- }
- }
- }
- /**
- * Get the instance of the configuration file
- * @ Return
- */
- Public
Properties getproperties (){
- Return
P;
- }
- /**
- * Test the main program
- * @ Param ARGs
- */
- Public
Static
Void
Main (string [] ARGs ){
- Configation c = new
Configation ();
- C. setdaemon (true
);
// Set the thread as the daemon thread
- C. Start (); // start the thread
- Try
{
- Thread. Sleep (3000
);
- } Catch
(Interruptedexception e ){
- E. printstacktrace ();
- }
- // Print the value of the configuration file repeatedly. The value takes effect 1 second after the configuration file is modified.
- While
(
True
){
- Properties P = C. getproperties ();
- System. Out. println (P. getproperty ("com. test."
));
- }
- }
- }
Where C. setdaemon (true) sets the thread as the daemon thread, about the daemon thread can refer to the http://www.google.cn/search? Complete = 1 & HL = ZH-CN & Q = Java + % E5 % AE % 88% E6 % 8A % A4 % E7 % Ba % BF % E7 % A8 % 8B & meta = & AQ = T & OQ = Java + % E5 % AE % 88% E6 % 8A % A4