Single thread to handle queue based logging
Usually I can figure problems I run into on my own with a little reading and experimenting, but this one has me stuck. All I am doing is creating a thread subclass that loops, pulling items off queue and writing to file. The problem I run into is that absolutely nothing is being written to disk. I came up with this design from a link in this thread: http://www.java-forums.org/threads-s...eaded-app.html, using BlockingQueue. Here is the thread subclass which handles the queue and writing the items to disk:
Code:
public class server_log extends Thread {
static final String newline = System.getProperty("line.seperator");
final private String LOG_FILENAME = "searchserver.log";
private BlockingQueue<String> log_queue = new ArrayBlockingQueue<String>(50);
private PrintWriter log_file = null;
public server_log() throws IOException {
log_file = new PrintWriter(new FileWriter(LOG_FILENAME, true), true);
start();
}
public void add_log(String log_data) {
try {
log_queue.put(log_data);
} catch (InterruptedException e) {
System.out.format("Problem adding to log queue\n");
}
}
public void shutdown() throws IOException, InterruptedException {
log_queue.put("SHUTDOWN");
log_file.close();
}
// ***Thread - Pulls items off queue and writes to disk
@Override
public void run() {
String log_data;
Date present;
DateFormat dateFormatter = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, new Locale("en","US"));
do {
try {
log_data = log_queue.take();
System.out.format("'" + log_data + "' taken from queue\n");
} catch (InterruptedException e) {
log_data = "SHUTDOWN";
}
if(log_data.equals("SHUTDOWN"))
return;
else {
present = new Date();
log_file.print("[" + dateFormatter.format(present) + "]: " + log_data + newline);
System.out.format("'" + log_data + "' written to log\n");
}
} while(! log_data.equals("SHUTDOWN"));
}
}
In my main thread, I wrote:
Code:
public class searchserver implements Runnable {
static server_log log;
And when I wanted to start the logging thread, in main() method:
Code:
log = new server_log();
I added a few lines to print output to console for debugging purposes, and this is the output I'm receiving:
Code:
'Index file loaded successfully.' taken from queue
'Index file loaded successfully.' written to log
'Server bound on port: 31337' taken from queue
'Server bound on port: 31337' written to log
'Server started successfully!' taken from queue
'Server started successfully!' written to log
I'm guessing it is something elementary, but I have read up on multithreading from numerous resources, from books to the Oracle.com site, and spent some time brushing up on the file i/o operations as well, and cannot seem to figure out what is causing nothing to be written to the log file. Any help would be greatly appreciated!