Logger disabled in shutdown hook thread

Hi, all,
In a shutdown hook thread, i want to keep a log using jdk1.4's logging class as following:
public void run(){
synchronized(this){
logger.info("System Shutdown");
But the logger does not work. Does anybody have the idea?
I create the logger with the following:
FileHandler fh = new FileHandler("MyLog.log");
fh.setFormatter(new CCXmlFormatter());
logger=Logger.getLogger("MyLog");
logger.addHandler(fh);

Please accept my appology for the off subject materiel. I just finished writing this and do not want to edit...
There is a design problem in the MemoryHandler class in that the close() method does not invoke push() as might be expected because most close() methods do flush buffers. This problem is exacerbated by the fact that LogManager registers a shutdown hook that closes all handlers. The log manager shutdown hook also does not invoke push() for memory handlers. Thus it is incumbent upon the user to invoke push() prior to shutting down. It would be natural to do this in a shutdown hook inside of a configureLogger() method. For example,
private static Logger configureLogger() {
Logger logger = Logger.getLogger("com.javarules");
logger.setLevel(Level.ALL);
try {
target =new FileHandler("%t/javarules.log",20000,1);
target.setFormatter(new SimpleFormatter());
} catch(IOException e) {
e.printStackTrace();
System.exit(1);
memoryHandler = new MemoryHandler(target,
2000,
Level.SEVERE);
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
memoryHandler.push();
logger.addHandler(memoryHandler);
logger.setUseParentHandlers(false);
return logger;
The problem with this is that shutdown hooks are a bunch of unstarted threads that the JVM runs concurrently. There is no guarantee this shutdown hook will run before the log manager closes the handler. (In my experience, the log manager shutdown hook runs first most of the time.)
Closing a memory handler does two things. The target handler is closed and the memory handler level is set to OFF, which means that when your shutdown hook runs, nothing is published and the push() method completes normally. In single-threaded applications memory-Handler.push() can be invoked at the bottom of the main method. GUI applications should invoke it in AWTExceptionHandler (or whatever you call your top-level exception handler) as well as the windowClosing (WindowEvent e) method.
There is actually a larger design issue than not being able to invoke push() in a shutdown hook. Should the LogManager class be registering a shutdown hook that invokes reset()? The API docs for that method read as follows.
Reset the logging configuration.
For all named loggers, the reset operation
removes and closes all Handlers and (except
for the root logger) sets the level to null.
The root logger's level is set to Level.INFO.
Bug Id 4682478 addresses this question, but misses the mark because it suggests an ordering (or reordering) of shutdown hooks. The evaluation correctly notes that it �is dangerous to rely on ordering of shutdown operations.� As noted above, shutdown hooks are a bunch of unstarted threads that a JVM starts and runs concurrently. They are not and never will be ordered. See java.sun.com/j2se/1.3/docs/guide/lang/hook-design.html for a discussion. The question, however, is not the fact that shutdown hooks are unordered. The question is should the log manager be closing handlers. In other words, should LogManager be registering a shutdown hook at all? If the answer is yes, the only plausible explanation is the push() method in a memory handler, which explains why I began this section with a discussion of that method. There is no documentation to support this theory (which in and of itself is a problem), but it is at least possible that the Cleaner thread (which is the name of the shutdown hook registered in LogManager) is designed precisely so that application programmers would not use the logging API in a shutdown hook. Logging one or two messages in a shutdown hook would not be a problem, but invoking push() for a memory handler that has thousands of log records that must be both localized and formatted could be a problem. As noted in the addShutdownHook(Thread hook) method:
Shutdown hooks should... finish their work
quickly. When a program invokes exit the
expectation is that the virtual machine will
promptly shut down and exit. When the virtual
machine is terminated due to user logoff or
system shutdown the underlying operating
system may only allow a fixed amount of time
in which to shut down and exit. It is there-
fore inadvisable to attempt any user
interaction or to perform a long-running
computation in a shutdown hook.
I think this warning should suffice, however, and that the logging API should be usable in a shutdown hook. At a bare minimum the LogManager class should document the rationale for making the logging API unavailable during shutdown.

Similar Messages

  • Starting new threads from within shutdown hooks

    I'd like to discuss this statement from the java 6 API:
    "A shutdown hook is simply an initialized but unstarted thread. When the virtual machine begins its shutdown sequence it will start all registered shutdown hooks in some unspecified order and let them run concurrently. *When all the hooks have finished it will then run all uninvoked finalizers if finalization-on-exit has been enabled. Finally, the virtual machine will halt*. Note that daemon threads will continue to run during the shutdown sequence, as will non-daemon threads if shutdown was initiated by invoking the exit method. "
    Now, my question is this: If I have a hook that starts a new non-daemon thread and then goes on to complete it's run() method, will the JVM finalize and halt? Or will it wait for my new thread to complete as well?
    I trust the specification, and believe that the JVM will either not allow me to create the thread or will finalize and shutdown even if it is running. However it's not explicitly stated anywhere, and I think that it's a hole in the documentation.
    I'm going to write a test case for this now. But chime in if you have thoughts.

    This is what happens if you start a new thread from a shutdown hook and do not wait for it to finish:
    public class ShutdownTest {
        private static class Shutdownhook extends Thread{
            public void run() {
                System.out.println("Shutdownhook starting");
                Thread t = new Thread(){
                    public void run(){
                        System.out.println("Thread successfully started");
                        try{ Thread.sleep(5000); }
                        catch(Throwable e){ System.out.println("Throwable from sleep: "+e); }
                        System.out.println("Thread successfully finished");
                t.start();
                //try {t.join();} catch (InterruptedException e) {}
                System.out.println("Shutdownhook completing");
        public static void main(String[] args) {
            Runtime.getRuntime().addShutdownHook(new Shutdownhook());
            System.out.println("Exiting from main()");
            Runtime.getRuntime().exit(0);
    Exiting from main()
    Shutdownhook starting
    Shutdownhook completing
    Thread successfully startedHowever, as you might expect, if you join() or wait for the thread's isAlive() to return false, you will be able to complete the thread.
    I'll leave someone else to figure out if that new thread gets finalized and if finalizers on exit is on, what happens. Mostly because it doesn't matter for my purposes.
    Enjoy

  • Xrs option and shutdown hooks

    I want to use a Java program as a service on Windows NT. I pass the -Xrs option to the VM in order to prevent it from stopping when a logoff signal is sent by the system. A problem occurs when I try to add a shutdown hook in my Java program, the following error is printed and the JVM aborts:
    Exception in thread "main" java.lang.IllegalArgumentException: Signal already used by VM: SIGINT
    at sun.misc.Signal.handle(Signal.java:152)
    at java.lang.Terminator.setup(Terminator.java:42)
    at java.lang.Shutdown.add(Shutdown.java:88)
    at java.lang.Runtime.addShutdownHook(Runtime.java:193)
    Does anybody know if this is normal behaviour, or is there a bug in the JVM?

    I have the same trouble, do you find a solution to solve it?
    I want to use a Java program as a service on Windows
    NT. I pass the -Xrs option to the VM in order to
    prevent it from stopping when a logoff signal is sent
    by the system. A problem occurs when I try to add a
    shutdown hook in my Java program, the following error
    is printed and the JVM aborts:
    Exception in thread "main"
    java.lang.IllegalArgumentException: Signal already
    used by VM: SIGINT
    at sun.misc.Signal.handle(Signal.java:152)
    at
    at
    at java.lang.Terminator.setup(Terminator.java:42)
    at java.lang.Shutdown.add(Shutdown.java:88)
    at
    at
    at
    t java.lang.Runtime.addShutdownHook(Runtime.java:193)
    Does anybody know if this is normal behaviour, or is
    there a bug in the JVM?

  • Closing the JWS Applet: shutdown hook is not invoked

    Windows 2000, Java Web Start 1.4.2_05
    I am running my applet with Java Web Start.
    If I close the JWS Applet window by clicking the upper right "X" button, the applet is being shut down.
    I want to perform a task like showing a warning message, before the applet disappears, but even if I implement the "Shutdown Hook", the according methods are not invoked by JWS.
    Does anybody know, how I can prevent the JWS window from being closed without notifying my applet?

    Another idea: Is it perhaps possible to disable/remove the "X" button from the JWS applet window?

  • Shutdown hook not getting called when running tomcat as a service

    I have a shutdown hook as part of a lifecycle <Listener> tomcat6 class, which gets created and registered in the class's constructor (class is referenced in the server.xml). The hook gets called during shutdown when tomcat has been started from a shell, but not when tomcat has been installed as a service. The -Xrs flag doesn't make a difference either way. I am running java 6u12 server VM (haven't tried client) and prior versions. Does anyone have any ideas? This has been tested by starting/stopping from the Control Panel, and also with 'tomcat6 //TS/ServiceName' (i.e. in test mode)
    One possibility is that tomcat internally calls Runtime.halt(), but the shutdown process appears to be normal and the same with either scenario. The other possibility is that the JVM has an issue. The tomcat user groups don't have anything to offer.
    Thoughts?
    tia

    sanokistoka wrote:
    jschell wrote:
    sanokistoka wrote:
    Let me ask the last question in a better way: Does anyone have any GOOD ideas?Get back to us when you have found your good solution.Stop wasting bandwidth. I didn't post here to be a smart ars like you and pretend that I have a solution to a rare problem... FYI - the workaround is to use the tomcat lifecycle events (AFTER_STOP_EVENT) to achieve the same - why do you think I mentioned it's a tomcat listener in the first place? Feel free to educate me.
    So you are claiming that Runtime.getRuntime().addShutdownHook() that you posted in the above is not part of the java API?
    Or perhaps that everything that is added via addShutdownHook() runs?
    Surely you are not claiming that it isn't calling addShutdownHook() in the first place?
    Get a life and a job.I have both but thanks for the concern.
    sanokistoka wrote:
    swamyv wrote:
    There are free tools available to debug windows. I think gdb is one of them. If you search you can find some good tools.
    If you find any good tools that you like share it with us.
    Yes I will try gdb (have cygwin) and see where this takes us - not sure if the JVM or tomcat6.exe have the symbols to get a meaningful stack trace. As luck would have it, [https://issues.apache.org/bugzilla/show_bug.cgi?id=10565|https://issues.apache.org/bugzilla/show_bug.cgi?id=10565] claims that "shutdown hooks are not supported in a container environment" although there is no such restriction in the servlet spec, which would make this a tomcat issue (it does sound like that tomcat6.exe wrapper is somehow involved). Unfortunately, tomcat does NOT issue the AFTER_STOP_EVENT if killed before it has completed its start-up (it appears its own shutdown hook, which sends the event, is not registered until it has fully come up); thus the need for a shutdown hook (at least, up until it's fully up). A shutdown hook is still required in my case for clean-up after tomcat is completely out of the picture. It sounds like the proper architecture here is to really embed tomcat in an application, and create a shutdown hook at the outer level.
    Educate me some more. The above description certainly seems like you are suggesting that both of the following are true.
    1. It is not a bug in the VM.
    2. The problem, for your implementation, is in how the wrapper terminates the windows service.
    Perhaps what is actually happening it that addShutdownHook() is never being called at all? Thus of course any processing of the thread associated with that would never, ever run.
    And that happens because you are banging on the stop service so fast that it doesn't actually have time to spin up?

  • Shutdown hook not called when hitting ctrl-c

    Hello
    I was expecting to be able to do clean-up (using a shutdown hook) when my application was terminated by a ctrl-c with the following code. But if the process is busy doing something (and not sleeping as is the case in all examples I've been able to find) the VM will not run it's hooks, so it seems.
    Am I missing something??
    public class ShutdownHook
    public static void main(String[] args)
    Runtime.getRuntime().addShutdownHook( new Thread() { public void run() { System.out.println("shutdown"); }});
    for (int j = 0; j < 10000; j++)
    System.out.println("run");
    // if the sleep is uncommented ctrl-c will work (99% of the time or so)
    // Thread.sleep(100);
    Regards,
    Jesper

    Cross-post. Original thread (with replies) is located at:
    http://forum.java.sun.com/thread.jspa?threadID=691132
    Kaj

  • 1.4 Logging (shutdown hook question really)

    If I have a handler configured and log a record inside a thread running as a shutdown hook, more times than not I get nothing in the log file (or console, or wherever) and have to resort to System.err.println().
    Now, from studying the code for LogManager this turns out to be the result of the inner Cleaner thread (which is the log managers shutdown hook) calling reset() on the manager.
    So, this question morphs itself into how to get my shutdown hook to run before the one that resets the log manager.
    Any ideas or adjsting the priority (order of execution) of shutdown hooks?

    Guys (silkm, trejkaz and the good doctor),
    That's for the input. Appreciate it.
    On shutdown hooks being bad design - interesting. In the case I'm thinking of, the entry point class for a distributed task manager (see http://forum.java.sun.com/thread.jsp?forum=4&thread=335843&tstart=0&trange=30) is "embedded" in consumer code and does indead have a clean shutdown method that we hope the consumer code will invoke before shutting itself down. But in the same was as the logging subsystem can not rely on it's consumer code to "do the right thing", we can't rely on our consumer code to behave itself. In addition, we do want to catch the case where an operator re-starts the consumer system (internal procedure demands unix processes are sent an interrupt rather than a kill). The code invoked by the clean shutdown and the caught shutdown persists (as XML) the state of the task manager which is read on re-start to perform recovery operations. Now, before you all dive in and say "save the state every time it changes" let me say that the state changes very rapidly and the I/O overhead of saving it is considerable. Also, having a background thread that persists state on a regular basis was considered, but it introduces the problem that it becomes different to gaurantee the validity of the persisted state.
    On setting the thread priority - that had occured to me and I shall be using this as one of my test cases to see what happens. As mentioned, the effects this has will vary by platform and VM. However, as the component in question will be running in a controlled environment we should be able to pick a configuration that works.
    On Linux threads and processes - Good point. But do unstarted threads have a process? This is significant to us as the target platforms for the task manager are Solaris and Linux.
    On java.lang.Runtime's implementation of shutdown hooks - I tend to agree that it's a bit simplistic. Maybe we should raise a change request to allow greater control over how hooks are executed.
    Thanks again and please chip in if you have any other ideas.

  • Shutdown hook

    I have a java program with a main method implementing shutdown hook.
    public static void main(String[] args) throws EcwException {
    CreateAllCharts createAllCharts = new CreateAllCharts();
    Runtime.getRuntime().addShutdownHook(new Thread() {
    public void run() {
    log.fatal("Shutting down operation.");
    This program is run from a korn shell script. When I do a ^c on the script, i dont see the 'fatal' message in the log. ???
    Can someone explain this.
    thanks.

    Instead of a well-handledSystem.exit(0)your ^C is (I believe) the equivalent ofRuntime.halt(), which deliberately doesn't give shutdown hooks the chance to run.
    What if your shutdown hook (I know it doesn't, but what if it did) got into a super gruesome wordy longsmith kind of loop and never exited? This is the reason for allowing the break-key to butt in, no matter what's executing.
    Could your app listen out for another key combination and leave ^C as an 'emergency exit' option? It's difficult for a console app I know but I think that's your best option.
    I'll watch closely for better advice than mine but, in the meantime, hope it helps.
    Chris.

  • How do you disable "Run with Multiple Threads" in a standalone EXE

    I have a program written in Labview 6.1.  After moving to a different hardware platform, my program has started crashing at the same point every time it is run.  I eventually found out that the cause of the crash is the fact that the new hardware has a dual core processor.  I confirmed this by disabling "Run with multiple threads" and now the program works fine.  What I need to know now is how to disable the same setting in a built EXE file, since as far as I know the "Run with multple threads" setting only affects execution in the Labview Dev environment.
    Thanks for any help,
    Dave

    Greg McKaskle once posted that using a non-reentrant (VI is NOT re-entrant) wrapper VI to make the calls to the dll will prevent simultaneous execution of the dll.
    Ben
    Ben Rayner
    I am currently active on.. MainStream Preppers
    Rayner's Ridge is under construction

  • Shutdown hooker, how does it work?

    hello All:
    I am writting a Java service that might crash for unknown reasons. As a failover mechanism, i was thinking to use shutdown hook to do house cleaning work such as closing db connection, notifying the client of this service, etc.
    However, people point it out that #1, inside shutdown hook it is ok to close db connection, but notifying client won't work; #2, shutdown hook is not reliable and likely not be called in the first place when the system crashes. Like that in the Linux env, it can be killed by "kill" or "kill -9", the impact on the service can be different.
    Anyone can make a comment about the above statements? And what's the best options in a crashing sceanario?
    Thanks,
    Sway

    mlk wrote:
    pierrot_2 wrote:
    Right, if I knew I had to pucker up, I'd put my head between my legs first... but there's no way to tell. Is there anything else you can use to moniter external conditions -- a backup battery?Some UPSes can inform the host that is has lost power and should shut down (but that is not a Java problem but a general OS/server setup issue). But you can't guard against everything (kill -9, running on a VM and someone killing your VM in that). The best you can do is attempt to make sure that you leave the world in as sane state as possible (for example good use of transactions) and make sure your monitoring solution works.Best example of that I ever encountered was a computer with 2 independent power supplies hooked up to an extension cable with a splitter, going into a single UPS and a single wall outlet.
    Someone tripped over the cable, pulling it out of the UPS outlet, thus killing the power to the machine past the point where the UPS is set to guard against power failure, and due to the idiotic arrangement which compromised the very reason (failsafe) there were 2 power supplies causing the machine to turn off.
    No amount of software can guard against such stupidity, yet we were told to modify the software so that it would continue to run in case of power failure (not joking, really happened).
    After much debate we modified it to constantly monitor and document its own state so it could restart where it left off before a power failure.

  • WebLogic AdminServer not starting: JVM Called WLS Shutdown hook

    Hi All,
    I am getting below error while starting the WLS Admin Server:
    <Nov 9, 2012 11:36:42 AM PST> <Notice> <WebLogicServer> <BEA-000388> <JVM called WLS shutdown hook. The server will force shutdown now>
    <Nov 9, 2012 11:36:42 AM PST> <Alert> <WebLogicServer> <BEA-000396> <Server shutdown has been requested by <WLS Kernel>>
    <Nov 9, 2012 11:36:42 AM PST> <Notice> <WebLogicServer> <BEA-000365> <Server state changed to FORCE_SHUTTING_DOWN>
    Any pointers for resolving this issue?
    Regards,
    Sunny

    What other errors can you see in your console ?
    When are you getting this error ?
    Does you coming in Running mode any time or are you getting this error while starting server ?
    Have you killed all the other processes ?
    You can try with :
    JAVA_OPTIONS="${JAVA_OPTIONS} -Djava.awt.headless=true -Xrs"

  • ImageIO - uses shutdown hooks

    Hi all,
    I'm developing a ray tracing app in Java and want to trap the JVM shutdown in order to save the current image before the application exits.
    Obviously I've tried to register a shutdown hook to perform the necessary clean-up BUT ... it appears that ImageIO.createImageOutputStream also tries to add a shutdown hook. This means that I can't save the image in my own shutdown hook (because the JVM denies ImageIO's shutdown hook due to a shutdown being in progress).
    Is there any way around this? Is there an alternative way I can trap the shutdown even BEFORE the JVM flips to "shutting down" state?
    Thanks in advance,
    Ian.

    I'm amazed Java doesn't include a simple "I'mabout
    to shutdown, but I'm not shutting down quite yet,so
    do stuff now please" event...I'm not amazed at all. Since you can't even clearly
    specify what it's doing, how should it be
    implemented? Either you shut down or not.Yes, I guess I didn't explain it very well :-)
    Anyhow, I've had to resort to trapping signals now to make it work. It does exactly what I need it to but I'm still worried about it being supported in the future and/or on other JVMs.
    Thanks for the advice so far.
    Ian.

  • Shutdown hook question.

    I want to add a shutdown hook to my program printing the last exception being thrown in my program, printing information similiar to exception.printStackTrace. In other words, i want to see the exception that caused my program to halt abnormally.

    A shutdown hook isn't going to be of much help since you'll have to record that last exception somewhere for the shutdown hook to process, and you might as well have printed it then.

  • Disable schedule shutdown

    I used command line in terminal to schedule my mac to shutdown, now I want to disable that schedule, but don't know how, please help.

    I'm using AMD, but xsensors says that I'm running ~90C, which seems super high, actually.  Why doesn't Windows or Ubuntu make me shut down?  Is it just that Arch makes my system run hotter?  I installed laptop-tools, but didn't configure it as I didn't understand how, and it doesn't seem to be helping.  And neither is that extra line i put in the kernel line of menu.lst that I found in the [SOLVED] Huge power consumption after upgrading kernel thread.
    Any other ideas?  I just had to reinstall GRUB and such because the system shut itself down during the middle of an upgrade.  Pain in the butt.

  • Activating or kicking off a shutdown hook?

    The Java 1.3 SDK API writes the following about shudown hooks:
    The Java virtual machine shuts down in response to two kinds of events:
    The program exits normally, when the last non-daemon thread exits or when the exit (equivalently, System.exit) method is invoked, or
    The virtual machine is terminated in response to a user interrupt, such as typing ^C, or a system-wide event, such as user logoff or system shutdown.I was wondering whether any of these events can be generated from a batch file. The reason behind this is that i would like a Java program to be shutdown remotely and not having to be in front of the computer pressing CTRL+C.
    Thank you in advance.

    I was wondering whether any of these events can be
    generated from a batch file. The reason behind this is
    that i would like a Java program to be shutdown
    remotely and not having to be in front of the computer
    pressing CTRL+C.In a unix environment the process is shut down with a signal. As an alternative to being generated from the keyboard these can be generated by the "kill" command.

Maybe you are looking for

  • Just looking for some advice for a Networking 'noob'

    Hey folks, I manage the post-production workflow for a small agency. We're getting ready to move into a new office space, and we'll be looking to make some upgrades to our video workflow and data management. At the current time, we have two G5s (Powe

  • Tab groups

    I'm working on a complex application that dynamically creates large Flex forms based on XML values from a server. There is a bug, where under certain conditions, tab groups are formed within a form -- tabbing loops through fields 4 to 8, when a radio

  • Java 2 Platform Standard Edition (J2SE) 5.0 Release 1

    I'm trying to use Shutterfly, an on-line photo service and am having problems. They recommended checking on my Java edition. I did at the Java check version site and got this report "You do NOT have the latest version of Java software. The latest ver

  • Adding check box in selection screen

    Hi all, I have to add a check box to the previous report, I need to fetch the data based on the checkbox. Please tell me how to proceed further with flag set. Thanx and Regards, Line.

  • Adobe Camera Profiles in Lightroom 2.4

    Hello, I upgraded to Lightroom 2.4, and installed Camera Raw 5.4. The Sony  A330 is on the support list now. However, I cannot see the profiles under camera calibration in the develop tab. What gives with this? I shut down and reopened, but no good.