Solved

How to know if another JVM is running?

Posted on 2006-07-20
56
1,640 Views
Last Modified: 2010-05-12
Dear Experts,

I need to figure how to notify myself when my Java application stops running.  I'm imagining another Java application, running in a separate JVM, that acts as a daemon and does nothing but check if the other application is running.  It will email me if not.  It will sleep most of the time.

I must use another JVM, because my customer ends my application by killing the entire JVM.  


Is there any way for a class in one JVM to know if another JVM is even running? (I'm running on Windows.)

If so, is there any way to know which classes the other JVM has loaded?

BTW, I know I can solve this by having the watcher check for any changes in my application's log file, but that's not ideal.  It would be better to check directly if I can.

Thanks!
BrianMc1958
0
Comment
Question by:BrianMc1958
  • 14
  • 13
  • 13
  • +5
56 Comments
 
LVL 86

Expert Comment

by:CEHJ
ID: 17145986
It would be easy if you were to arrange for the first app to open a Socket. The second can try likewise on the same port
0
 
LVL 8

Expert Comment

by:colr__
ID: 17145996
Could you not override finalize() in the Object class to do this?
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 17146009
You could also get the first app to create a lock file
0
 
LVL 30

Expert Comment

by:mayankeagle
ID: 17146029
>> I need to figure how to notify myself when my Java application stops running.  

Use a shut-down hook to send yourself an alert (through e-mail, etc) in your Java app. No other apps required.
0
 
LVL 30

Expert Comment

by:mayankeagle
ID: 17146039
>> I'm running on Windows

You can also write native code in Windows to get the list of currently running processes - you could deploy it as a Windows service which runs forever and checks if the Java app has stopped periodically. I'd still prefer the shut-down hook (it will be invoked before the JVM exits).
0
 
LVL 30

Expert Comment

by:mayankeagle
ID: 17146051
http://javaalmanac.com/egs/java.lang/ExitHook.html

>> It would be easy if you were to arrange for the first app to open a Socket. The second can try likewise on the same port

CEHJ, I hope you didn't mean that as a production solution ;-) ? Why open a port.... the same port might be required by another app. Of course the file-lock is better.
0
 
LVL 24

Accepted Solution

by:
sciuriware earned 500 total points
ID: 17146054
Very simple by a lock file:

import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.io.File;
import java.io.RandomAccessFile;

/* Provides instance or group solitarity (=only one instance allowed at a time).
 * The implementation is platform independent since MSWindows98, LINUX-2 and
 * UNIX SVR4, and can be deployed as an inter-process synchonisation tool.
 *
 * @author     J.F.Lanting
 * @since      07-Oct-2002
 */

/*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*/
/*    APPLICATION SOLITARITY:                                                */
/*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*/

public class Solitarity
{
static String programName; // Fill in yourself .....

static String userName = System.getProperty("user.name");

   /**
    * Lock to be applied on the solitarity file.
    */
   private static FileLock solitarityLock = null;

   /**
    * Channel of the solitatity file to lead locking.
    */
   private static FileChannel solitarityChannel = null;

   /**
    * Token file which locking signals solitarity.
    */
   private static RandomAccessFile solitarityFile;

   private static String getTempDirectory()
   {
      return(System.getProperty("java.io.tmpdir") + '/');
   }


   /**
    * Sets / tests for a mutual application instance lock on a temporary lockfile.
    * <p>
    * Can be used to guarantee that only one instance of this application is running.<BR>
    * Returns <b>null</b> IF this is the only running application defined by the given token,<BR>
    * otherwise the name (only) of the other user who blocks you.<BR>
    * The lock must be removed by <b>Sy.unSolitaire()</b>
    * if the application must continue to run simultaneously with others.<BR>
    * The lock is effectively removed anyway when the application exits or crashes.<BR>
    * <b>NOTE:</b> the lockfile is NOT deleted on exit as it might be locked by an other process by then!
    * </p>
    *
    * @return null if you are the only instance, otherwise the name of the other user.
    */
   public static String solitaire()
   {
   String result = solitaire(programName);
   int index;

      if(result != null && (index = result.indexOf(" ")) > 0)
      {
         result = result.substring(0, index); // User name only!
      }
      return(result);
   }


   /**
    * Sets / tests for a mutual application instance lock on a temporary lockfile.
    * <p>
    * Can be used to guarantee that only one member of an application group is running.<BR>
    * Returns null IF this is the only running application defined by the given token,<BR>
    * otherwise the name and the program of the other user who blocks you.<BR>
    * The lock must be removed by <b>Sy.unSolitaire()</b>
    * if the application must continue to run simultaneously with others.<BR>
    * The lock is effectively removed anyway when the application exits or crashes.<BR>
    * <b>NOTE:</b> the lockfile is NOT deleted on exit as it might be locked by an other process by then!
    * </p>
    *
    * @param token identification for the group the be solitair in.
    * @return null if you are alone or the other user if not.
    */
   public static String solitaire(String token)
   {
   String mark;                        // Readable mark in the lock file.
   File solitarityLockFile;            // To detect existence only.
   boolean myLockFile;                 // If there was no lock file..

      if(solitarityLock != null)
      {
         return(null);        // Having a lock myself : already secured it.
      }

// The first 8 bytes of "mark" are the lock area.

      mark = "LOCK BY " + userName + " running \"" + programName + "\"\n";
      solitarityLockFile = new File(getTempDirectory() + ".solitaire_" + token);
      myLockFile = !solitarityLockFile.exists();

      try
      {
         solitarityFile = new RandomAccessFile(solitarityLockFile, "rws");
         solitarityChannel = solitarityFile.getChannel();
         if(myLockFile)
         {
            solitarityFile.writeBytes(mark); // Write NOW!
         }
         if((solitarityLock = solitarityChannel.tryLock(0, 8, false)) == null)
         {
            solitarityFile.seek(8);
            return(solitarityFile.readLine());
         }
         if(!myLockFile)               // But locked by me, so mark it.
         {
            solitarityFile.writeBytes(mark); // Write (delayed).
         }
      }
      catch(Exception e)
      {
         return("somebody(!?)");       // No access? or not alone!
      }
      return(null);
   }


   /**
    * Releases an application lock set by <b>Sy.solitaire()</b>.
    * <p>
    * This methods gives way to other applications, although any lock of this kind<BR>
    * is automatically removed at exit or when the application crashes.
    * </p>
    */
   public static void unSolitaire()
   {
      try
      {
         if(solitarityLock != null)
         {
            solitarityLock.release();
            solitarityLock = null;
            solitarityChannel = null;
         }

         if(solitarityFile != null)
         {
            solitarityFile.close();
            solitarityFile = null;
         }
      }
      catch(Exception e)
      {
         System.out.println(":\n:: FAILED TO UNLOCK SOLITARITY LOCKFILE");
      }
   }
}

// So all you have to do is let the first application set this "solitarity-lock"
// and have another one test it from time to time.
// The lock goes away after exit, kill or crash.

;JOOP!
0
 
LVL 24

Expert Comment

by:sciuriware
ID: 17146066
A shutdown hook may not work when the application is killed.
The sample code above can also REUSE the lock, passing it from application to application.
;JOOP!
0
 
LVL 30

Expert Comment

by:mayankeagle
ID: 17146106
>> my customer ends my application by killing the entire JVM.  

It will work for these cases (normal termination) if the requirement is to trap only those.

Somehow I don't like the idea of having another process running all the time simply for checking if this one is alive or not....
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 17146150
Yes - my second suggestion was better than my first ;-)
0
 

Author Comment

by:BrianMc1958
ID: 17146153
Yikes!  

To mayankeagle:  WHAT is a shut-down hook?  That sounds ideal.  Whatever it is, will it still work even when the JVM itself is being manually shut down?  What about when the server itself is shutting down unexpectedly?  

To colr__ :  I've never actually used finalize().  

To everybody: I should have mentioned my application is fairly complex, and I have no idea which of many classes might be running when it ends (unexpectedly).  It does have some sort of "main loop", which controls all processing.  If I were to use a "shut-down hook" or finalize(), is that where it would go?  Assuming this is my app:

public class FS_MainDriver
{
  public static void main(String args[])
  {
    boolean done = false;
    while (!done)
      {
         // go do complicated things
      }
  }
}



0
 
LVL 8

Expert Comment

by:colr__
ID: 17146175
finalize() will be called when an object is destroyed. Ive never actually used it either, but I suspect it might be useable by yourself to detect the shutdown of the app, regardles of where it happans. Correct me if Im wrong people, I would like to know!!!

As standard it doesnt do anythign, although it still gets called on destruction of every object - you'd just override it to perform the functionality you want on the detsroying of the object.
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 17146202
You would use the lock file *in conjunction with* a shutdown hook, or another app won't be able to tell if it's running
0
 

Author Comment

by:BrianMc1958
ID: 17146240
Are "shut-down hook" and "finalize()" the same thing?
0
 
LVL 24

Expert Comment

by:sciuriware
ID: 17146270
colr_ , there is no finalize() at any ending of an application! That's the big complaint of proframmers against SUN.

;JOOP!
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 17146278
No. finalize pertains to class unloading, shutdown to vm shutdown

http://mindprod.com/jgloss/finalize.html
0
 
LVL 24

Expert Comment

by:sciuriware
ID: 17146280
A shutdown hook is a thread that should be executed by the call    System.exit();

;JOOP!
0
 
LVL 24

Assisted Solution

by:sciuriware
sciuriware earned 500 total points
ID: 17146318
public class FS_MainDriver
{
  public static void main(String args[])
  {
        Solitarity.solitaire("Token"); // That's all
    boolean done = false;
    while (!done)
      {
         // go do complicated things
      }
  }
}


The monitoring app does:

   while(sleep some seconds)
   {
        if(Solitarity.solitaire("Token") == null)
        {
 // it is gone ..

;JOOP!
0
 

Author Comment

by:BrianMc1958
ID: 17146503
To everybody:  Thanks for all the responses!  I won't have time to try them out until later in the day.  Will respond again then...  I'll still be reading, though, if anyone has anything else to say.  (Interesting topic, eh?  When a Java class in being unloaded, does it see some bright light or something?  Virtual angels?)

--BrianMc1958
0
 
LVL 24

Expert Comment

by:sciuriware
ID: 17147404
JAVA class unloaded? forget that.

Btw.: I use my solution when one of my apps re-installs a new version of itself.
The new version must wait until the old version, that started the new version has exited.
Works as a charm.

;JOOP!
0
 
LVL 30

Expert Comment

by:mayankeagle
ID: 17148426
>> When a Java class in being unloaded, does it see some bright light or something?

That's a different story altogether....
0
 
LVL 92

Expert Comment

by:objects
ID: 17150672
> You would use the lock file *in conjunction with* a shutdown hook, or another app won't be able to tell if it's running

another application would not need to tell if it was running.
shutdown hook is all you need.
0
 
LVL 30

Expert Comment

by:mayankeagle
ID: 17151739
Thanks Mick
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 17152229
>>another application would not need to tell if it was running

Why not?
0
 
LVL 35

Expert Comment

by:girionis
ID: 17152313
0
 
LVL 35

Expert Comment

by:girionis
ID: 17152347
0
 
LVL 30

Expert Comment

by:mayankeagle
ID: 17152663
>> Why not?

CEHJ, I don't like the idea of having another application running in the background, eating CPU and memory for nothing but just periodically checking if another application was running - do you think its a good idea?
0
 
LVL 24

Expert Comment

by:sciuriware
ID: 17152809
And I don't like "professional" situations where the only valid
ending for an application seems to be a killing by a customer.

;JOOP!
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 86

Expert Comment

by:CEHJ
ID: 17152965
>>do you think its a good idea?

It seems to me to be essential. How can an application that's *not* running check if it's running?
0
 
LVL 92

Expert Comment

by:objects
ID: 17152988
> do you think its a good idea?

absolutely not, especially as its unnecessary in this case. And do you run *another* application to make sure your monitor app is running :-D

Shutdown hook handles this situation just fine all by itself.
0
 
LVL 30

Expert Comment

by:mayankeagle
ID: 17152990
>> And I don't like "professional" situations where the only valid ending for an application seems to be a killing by a customer.

Obviously in professional/ production situations, anything can happen and the situations being referred to were not the only professional ones in case you mistook it. We never said that the application can be ended *only* by the customer. We said we wanted to know whether those were the only cases (normal terminations) that were relevant for discussion, or do we have to do this for abnormal termination too, because the way the question mentions it, it looks like normal termination is the only one we are interested in: >> my customer ends my application by killing the entire JVM.

>> How can an application that's *not* running check if it's running?

That's what - the requirement is for the running application to somehow inform before it shuts down - whether you use another application to trap it, or make the existing application use a shut-down hook is only a design consideration which comes later depending on whether you want to trap improper shut-down too, or only normal shut-down.
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 17153134
>>That's what - the requirement is for the running application to somehow inform before it shuts down

That's not the *whole* requirement:

>>my customer ends my application by killing the entire JVM.

A shutdown hook won't help you there

0
 
LVL 30

Expert Comment

by:mayankeagle
ID: 17153234
>> A shutdown hook won't help you there

Why? If the VM shut-down is not improper, it should be executed.

>> That's not the *whole* requirement:

Brian - pls clarify. Also how exactly does the customer shut down the VM?
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 17153257
>>Why? If the VM shut-down is not improper, it should be executed.

This to me sounds like the process will be killed

>>by killing the entire JVM

0
 
LVL 4

Expert Comment

by:astorer
ID: 17153342
Why not use JMX?
http://java.sun.com/products/JavaManagement/
Suggestions above *will* work but you are using your own techniques.  JMX can provide a way to manage what you want to do.  You'd still need that always running "Agent" to be able to start/stop your server but JMX can provide a mechanism to monitor whether the server is running without writing your own socket handling.

Also, there are many UIs that are available to provide a management view of your application.

This is the correct way to manage an application but is maybe not as lightweight as the suggestions above.

Andrew
0
 
LVL 92

Expert Comment

by:objects
ID: 17153448
> A shutdown hook won't help you there

rotfl, thats what shutdown hooks are for :-D

> Also, there are many UIs that are available to provide a management view of your application.
> This is the correct way to manage an application but is maybe not as lightweight as the suggestions above.

Absolutely right, if there is a need to monitor an application you don't go writing another application to do it. Thats just silly.
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 17153705
>>rotfl, thats what shutdown hooks are for :-D

So you think a shutdown hook will run if the process is killed do you? ;-)
0
 

Author Comment

by:BrianMc1958
ID: 17154024
I guess I did pick an interesting topic.

>>Brian - pls clarify. Also how exactly does the customer shut down the VM?

In general, I need a way to know if my app has stopped running REGARDLESS of WHY.  It should run 24/7, although it sleeps most of that time.  Although there is a way to shut it down cleanly, my customer kills the JVM because it's quicker.

I have tested the shutdownhook, and it only works (here, anyway) when the JVM shuts down normally.  When I kill java.exe thru Windows Task Manager, it does not work.  (Neither does an overridden finalize()).

I'm about to try sciuriware's technique.  (It looks cool.)  I didn't want a whole other separate watcher either, but I can't see another way right now.  I will be able to schedule it to run hourly, anyway, which is good enough for me, and won't chew up a lot of resources.

As always, I'm very grateful you all would take so much time to answer my questions.  
0
 
LVL 30

Expert Comment

by:mayankeagle
ID: 17154044
>> When I kill java.exe thru Windows Task Manager, it does not work

Yes, in that scenario it won't.

>> I need a way to know if my app has stopped running REGARDLESS of WHY

I'm afraid in that case, you need to perhaps try the file-lock or maybe astorer's technique.
0
 
LVL 4

Expert Comment

by:astorer
ID: 17154679
Here's the JMX way...

You instantiate an MBeanServer and provide it with an MBean in your app that is used to report on whether your application is running.

A JMX client/Admin console is responsible for periodically checking that MBeanServer and checking to see whether your app is still alive.  If your app is not alive, the JMX client should raise a notification (just use log4j - you can then map that to a log file, send email, windows event log etc.)

That's how you'd usually do such a thing in an enterprise app.  
0
 

Author Comment

by:BrianMc1958
ID: 17154945
To astorer:  Thank you for your suggestion, but we've just got sciuriware's solution running, and we don't have time to look into yours.  Maybe next year...

To sciuriware:  Can't thank you enough.  It works beautifully.  Our customer (already) is very happy. My boss is very happy.  I am very, very happy.  I hope you are happy at least well into next week!

To everybody:  Once again, thank you all so much for your help.  This has been not only very important to my little company, but very educational and fun, too.  
 
0
 

Author Comment

by:BrianMc1958
ID: 17154967
p.s.:  To anyone reading this, sciuriware provided the core solution in the answer I'll "accept", and then the simple implementation in a later answer I'll also award points for.  Hope they add up OK...
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 17155022
>>Can't thank you enough.  It works beautifully.

Good. Yes - use a lock file as i mentioned ;-)

Out of interest, is it still working well when the process is killed?
0
 
LVL 24

Expert Comment

by:sciuriware
ID: 17155792
If so many people are happy, I'm honoured!

;JOOP!
0
 

Author Comment

by:BrianMc1958
ID: 17156478
>>Out of interest, is it still working well when the process is killed?

Yes.  I kill the whole JVM manually, and it works just fine.  The "watcher", of course, is running in a separate JVM, periodically.  So far it's been perfect.
0
 
LVL 30

Expert Comment

by:mayankeagle
ID: 17159951
You should've perhaps given some points to CEHJ too - he had suggested the same idea.
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 17160508
>>The "watcher", of course, is running in a separate JVM, periodically.

Ah OK - as i mentioned an app can't watch itself ;-)
0
 
LVL 24

Expert Comment

by:sciuriware
ID: 17160511
mayankeagle, sometimes the one who effectively gave the right answer is awarded,
then sometimes the one who made it ... digestible.
I'm sure you would have understood the first answer fully.
;JOOP!
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 17160528
Thanks for thinking of me mayank ;-)
0
 
LVL 24

Expert Comment

by:sciuriware
ID: 17160546
Hey CEHJ, I think of you all the time! How could I ignore someone with over 5 000 000 points in JAVA alone!

;JOOP!
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 17160550
;-)
0
 
LVL 24

Expert Comment

by:sciuriware
ID: 17160571
This should not be misunderstood by others .....
0
 
LVL 24

Expert Comment

by:sciuriware
ID: 17160574
Sorry it's 36 Celcius here ....
0
 
LVL 30

Expert Comment

by:mayankeagle
ID: 17162847
>> sometimes the one who effectively gave the right answer is awarded

Correct, nobody's denying your efforts ;-) just thought CEHJ deserved some of the points too for hinting in the right direction initially.
0
 
LVL 24

Expert Comment

by:sciuriware
ID: 17163225
You are so right. Yesterday I was ignored somewhere. The "asker" rules.
;JOOP!
0
 
LVL 30

Expert Comment

by:mayankeagle
ID: 17166210
Yeah, those happen very often :)
0

Featured Post

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

Suggested Solutions

For customizing the look of your lightweight component and making it look opaque like it was made of plastic.  This tip assumes your component to be of rectangular shape and completely opaque.   (CODE)
Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:
The viewer will learn how to implement Singleton Design Pattern in Java.

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

22 Experts available now in Live!

Get 1:1 Help Now