I'm using jdbc for the first time and reading from a file which contains sql queries I wrote earlier. Although the queries are properly executed and my program goes on without any apparent issue, After I've statement.executeBatch();, I cannot write anything into my log anymore.
-I'm using the java.util.logging to do my logging with a FileHandler. To read my ".sql" file, I'm using a BufferedReader and a FileReader. I know I'm not sharing a lot of code to fully understand the context, but that's all I have from memory. I'm closing all the readers after use.
Any ideas what could be the problem?
MyLogger.log(Level.WARNING, "it does write");
statement.executeBatch();
MyLogger.log(Level.WARNING, "it doesn't write anymore");
statement.close();
MyLogger.log(Level.WARNING, "still doesn't");
Thanks
edit: MyLogger is a class with a statig log method
edit2: #Tim Biegeleisen
statement.executeBatch() returns an array of int, one for each batch. I tried :
try {
int[] results = statement.executeBatch();
for (int result : results)
{
if (result == Statement.EXECUTE_FAILED)
{
MyLogger.log(Level.SEVERE, "batch failed, but driver seems to still be alive.");
System.out.println("batch failed, but driver seems to still be alive.");
}
}
} catch (SQLException e) {
MyLogger.log(Level.SEVERE, "the batch failed, and the driver died too.");
System.out.println("the batch failed, and the driver died too.");
}
and it printed and logged nothing.
edit3: I guess I was asking too much of my shutdown hook. I'm not familiar with it so I'm not sure what was precisely the problem.
The explanation which seems most likely to me is that your code is rolling over upon hitting executeBatch(). After this, the subsequent calls to the logger do not appear to be working, because they aren't being hit at all. One simple way to test this would be to surround your call to executeBatch() with a try catch block:
try {
int result = statement.executeBatch();
if (result == Statement.EXECUTE_FAILED) {
MyLogger.log(Level.ERROR, "batch failed, but driver seems to still be alive.");
}
} catch (SQLException e) {
MyLogger.log(Level.ERROR, "the batch failed, and the driver died too.");
}
I guess I was asking too much of my shutdown hook. I'm not familiar with it >so I'm not sure what was precisely the problem.
See: LogManager$Cleaner() can prevent logging in other shutdown hooks.
If you are trying to perform logging in a shutdown hook then you are racing with the LogManager$Cleaner thread.
As a workaround to creating a custom shutdown hook you can create a custom handler and install it on the root logger.
The first action of the LogManager$Cleaner is to close all the installed handlers on the logger.
Once the cleaner calls the close on the custom handler you can then do one of the following:
Have LogManager$Cleaner run your shutdown code inside the handler.
Find your custom shutdown hook using the Thread API and join with it which will block the cleaner thread.
Related
I have the following code:
public class LogWriter implements Runnable {
private static BlockingQueue<LogRecord> logQueue;
static {
logQueue = new ArrayBlockingQueue<LogRecord>(30);
}
#Override
public void run() {
Integer errorNo = 0;
configureLogger();
while (true) {
try {
LogRecord record = logQueue.take();
consumeLogRecord(record);
System.out.println(++errorNo + " - Logged error in file '" + LoggerConfig.LOG_PATH + "'");
record = null;
} catch (InterruptedException e) {
System.out.println(e.getMessage());
}
}
}
}
This is part of a logger for a LibreOffice pluggin written in Java. When LibreOffice is closing, it simply kills it's plugins (as I can tell so far, not sure of it), but not before sending a signal to them that it is closing, which I can detect in my code (through the UNO API). After I receive the termination signal from LibreOffice, I want to flush my LogRecord queue to the log file and change that while(true) to false so the method run() can finish appropriately, releasing the resources it have. So my question is, how can I tell the JVM that waiting for this operation is of high priority and it shouldn't terminate before finishing it?
The advice about shutdown hooks must be taken with a large grain of salt. The shutdown hook is a last resort device where you can try to salvage what you couldn't possibly by any other means. You can't rely on any normal assumption, such as that System.out is still open, that your log file is still open, that even the filesystem is available, and so on.
A use case for a shutdown hook is to try to gracefully close acquired resources, with no attempt at further data transfer.
The approach you should take is:
inform yourself exactly what terms LibreOffice gives you: do you have a certain timeout within which to complete your work?
minimize the work pending at any point in time, thereby maximizing your chance to have it completed within the timeout.
You can use.
Runtime.getRuntime().addShutdownHook(Thread);
Shutdown hooks will be the best option to go.
I am trying to execute external jar from java app.
What is the most elegant way to check if the process has been started successfully and running?
ExtApp.jar is long-term running process, so I can not use Process.waiFor() because it would block my app. I have come up with following code, with idea behind is that the exitValue() throws IllegalThreadStateException if the process has not been yet terminated.
boolean success = false;
try {
Process process = Runtime.getRuntime().exec("java -jar ExtApp.jar");
try {
if (process.exitValue() == 0)
success = true;
} catch (IllegalThreadStateException e) {
success = true;
}
} catch (Exception e) {}
System.out.println(success);
But it is kind of ugly solution. Any ideas for a better one?
There seems to be no elegant solution to the problem. E.g. I ran your code on my PC and got "success" though there is no ExtApp.jar on it. That is, from the point of view of Runtime.exec the process (java.exe) started successfully, no matter what happens afterwards.
The above seems very dubious. You're going to spawn off your process and then test it immediately. The process itself may not have determined whether it's running ok or not (e.g. when does it actually check that jar file eixsts/is loadable/is valid ?)
I think you're better off spawning the process via a new thread, calling/blocking in that thread via Process.waitFor() and then notifying the parent thread (via whatever means - state variable, wait()/notify(), a java.util.concurrent.Future etc.) once the process has exited and you've collected the exit status.
Apache Commons Exec is a useful library for doing this sort of work, including asynchronous spawning/notification of process exit. See the DefaultExecuteResultHandler for more info.
How to restart a transaction (so that it executes at least once) when we get:
( com.mysql.jdbc.exceptions.jdbc4.MySQLTransactionRollbackException:Deadlock found when trying to get lock; Try restarting transaction ) OR ( transaction times out ) ?
I'm using MySQL(innoDB ENGINE) and Java.Please help and also link any useful resources or codes.
When ever you are catching such type of exception in your catch block
catch(Exception e){
if(e instanceof TransactionRollbackException){
//Retrigger Your Transaction
}
// log your exception or throw it its upto ur implementation
}
If you use plain JDBC, you have to do it manually, in a loop (and don't forget to check the pre-conditions every time.
If you use spring, "How to restart transactions on deadlock/lock-timeout in Spring?" sould help.
I have a selenium script and I need to write the failures to a log file. For example if a page is not found or selenium.waitForPageToLoad expires. Instead of going straight to tearDown(), I would like to log why my script has stopped.
selenium.open("/confluence/login.action?logout=true");
selenium.type("os_username", "login");
selenium.type("os_password", "pw");
selenium.click("loginButton");
selenium.waitForPageToLoad("10000");
selenium.click("title-heading");
selenium.click("spacelink-INTR");
selenium.waitForPageToLoad("10000");
selenium.click("link=Create Issue Links");
selenium.waitForPageToLoad("10000");
selenium.click("quick-search-query");
selenium.type("quick-search-query", "create issue links");
selenium.click("quick-search-submit");
selenium.waitForPageToLoad("100000");
stoptime = System.currentTimeMillis();
Also would it be possible to skip a steap if it fails, right now if anything at all fails it will go straight to the teardown() method.
I am using java.
What you are asking is exception handling. If any of the steps in your tests fails then selenium will throw an exception and tests would stop. If you handle the exceptions using try catch then you should be able to achieve what you are looking for. As an example, see the code below. This would handle the initial page load timeout. Even if selenium.open fails, script will handle the exception and move ahead to next statement. You should read more about exception handling to find what is the best way to handle these exceptions.
try{
selenium.open("/confluence/login.action?logout=true");
}
catch(Exception e)
{
//Code to write data to a file goes here
System.out.println("Selenium open did not work")
}
I am using the Javamail API connecting to my IMAP server. Everything is working great with the javax.mail.Folder.idle() method. My listener gets called when a new mail comes in. However the problem is idle blocks forever, how do I interrupt it? How do I actually stop the listening without killing my Java program?
I've tried calling Thread.interrupt() on the idle'd thread. Nothing happens. I am running out of ideas.
Performing any operation on that folder (from another thread) will cause idle() method to return immediately. So if you want to forcefully interrupt it, just call close() from a new thread.
If you read the documentation properly, and read the source code, you'll realise that you have to create a new thread for calling .idle().
Allocate that thread to a variable, and whenever you want call the interrupt() on that thread, or just ignore notifications!
If you need to get idle() going again, just rerun the thread!
I created something similar, so you might wanna check it out.
https://github.com/mofirouz/JavaPushMail/blob/master/src/main/java/com/mofirouz/javapushmail/JavaPushMailAccount.java
Good luck
A proper way to abort IDLE command is the following snippet. Note that the Folder instance should be the same as the one used to start idling. I've tested the other solutions proposed on this thread but they didn't work in my case.
IMAPFolder folder = store.getFolder("INBOX");
try {
folder.doOptionalCommand("Abort IDLE error mesage", new IMAPFolder.ProtocolCommand() {
#Override
public Object doCommand(IMAPProtocol p) throws ProtocolException {
p.idleAbort();
return Boolean.TRUE;
}
});
} catch (MessagingException e) {
e.printStackTrace();
}