How to know if another JVM is running?

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
BrianMc1958Asked:
Who is Participating?

Improve company productivity with a Business Account.Sign Up

x
 
sciuriwareConnect With a Mentor Commented:
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
 
CEHJCommented:
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
 
colr__Commented:
Could you not override finalize() in the Object class to do this?
0
The 14th Annual Expert Award Winners

The results are in! Meet the top members of our 2017 Expert Awards. Congratulations to all who qualified!

 
CEHJCommented:
You could also get the first app to create a lock file
0
 
Mayank SAssociate Director - Product EngineeringCommented:
>> 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
 
Mayank SAssociate Director - Product EngineeringCommented:
>> 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
 
Mayank SAssociate Director - Product EngineeringCommented:
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
 
sciuriwareCommented:
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
 
Mayank SAssociate Director - Product EngineeringCommented:
>> 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
 
CEHJCommented:
Yes - my second suggestion was better than my first ;-)
0
 
BrianMc1958Author Commented:
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
 
colr__Commented:
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
 
CEHJCommented:
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
 
BrianMc1958Author Commented:
Are "shut-down hook" and "finalize()" the same thing?
0
 
sciuriwareCommented:
colr_ , there is no finalize() at any ending of an application! That's the big complaint of proframmers against SUN.

;JOOP!
0
 
CEHJCommented:
No. finalize pertains to class unloading, shutdown to vm shutdown

http://mindprod.com/jgloss/finalize.html
0
 
sciuriwareCommented:
A shutdown hook is a thread that should be executed by the call    System.exit();

;JOOP!
0
 
sciuriwareConnect With a Mentor Commented:
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
 
BrianMc1958Author Commented:
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
 
sciuriwareCommented:
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
 
Mayank SAssociate Director - Product EngineeringCommented:
>> When a Java class in being unloaded, does it see some bright light or something?

That's a different story altogether....
0
 
objectsCommented:
> 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
 
Mayank SAssociate Director - Product EngineeringCommented:
Thanks Mick
0
 
CEHJCommented:
>>another application would not need to tell if it was running

Why not?
0
 
girionisCommented:
0
 
girionisCommented:
0
 
Mayank SAssociate Director - Product EngineeringCommented:
>> 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
 
sciuriwareCommented:
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
 
CEHJCommented:
>>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
 
objectsCommented:
> 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
 
Mayank SAssociate Director - Product EngineeringCommented:
>> 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
 
CEHJCommented:
>>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
 
Mayank SAssociate Director - Product EngineeringCommented:
>> 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
 
CEHJCommented:
>>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
 
astorerCommented:
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
 
objectsCommented:
> 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
 
CEHJCommented:
>>rotfl, thats what shutdown hooks are for :-D

So you think a shutdown hook will run if the process is killed do you? ;-)
0
 
BrianMc1958Author Commented:
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
 
Mayank SAssociate Director - Product EngineeringCommented:
>> 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
 
astorerCommented:
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
 
BrianMc1958Author Commented:
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
 
BrianMc1958Author Commented:
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
 
CEHJCommented:
>>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
 
sciuriwareCommented:
If so many people are happy, I'm honoured!

;JOOP!
0
 
BrianMc1958Author Commented:
>>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
 
Mayank SAssociate Director - Product EngineeringCommented:
You should've perhaps given some points to CEHJ too - he had suggested the same idea.
0
 
CEHJCommented:
>>The "watcher", of course, is running in a separate JVM, periodically.

Ah OK - as i mentioned an app can't watch itself ;-)
0
 
sciuriwareCommented:
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
 
CEHJCommented:
Thanks for thinking of me mayank ;-)
0
 
sciuriwareCommented:
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
 
CEHJCommented:
;-)
0
 
sciuriwareCommented:
This should not be misunderstood by others .....
0
 
sciuriwareCommented:
Sorry it's 36 Celcius here ....
0
 
Mayank SAssociate Director - Product EngineeringCommented:
>> 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
 
sciuriwareCommented:
You are so right. Yesterday I was ignored somewhere. The "asker" rules.
;JOOP!
0
 
Mayank SAssociate Director - Product EngineeringCommented:
Yeah, those happen very often :)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.