If you want a Java Application to run one instance. Most will consider using JNDI technology to do this function in the namespace.
When C is developed under Windows, such a thing is easy, just create a semaphore.
This article is to use the JAVA's JNI technology to utilize the Windows signal kernel object, so that it is very easy to control the number of Java run instances.
As for JNI technology, it will not say much.
1. First, write the following Java code: / ** convenient, put all the code in a directory
Public class salesleapp {
Public native boolean FINDEXSIT (); // Native Method
Static {System.loadLibrary ("SingleApp"); /// load the native library}
Public static void main (string [] args) {boolean res = new salesLEAPP (). FINDEXSIT ();
If (res) {system.out.println ("Find An Instance"); System.exit (0);} else {system.out.println ("this is no one exsit!");} while (true) { }
}
Compile the class file with Javac.
2. Get the header file of C
Use the Javah tool to get the following header file: SingleApp .h
/ * Do Not Edit this file - it is machine generated * / # include
#ifndef _Included_singleApp # define _Included_singleApp # ifdef __cplusplusextern "C" {# endif / * * Class: singleApp * Method: findExsit * Signature: () Z * / JNIEXPORT jboolean JNICALL Java_singleApp_findExsit (JNIEnv *, jobject);
#ifdef __cplusplus} # Endif # ENDIF
3. Edit the C source file: SingleApp .cpp .cpp
#include
JNIEXPORT jboolean JNICALL Java_singleApp_findExsit (JNIEnv *, jobject) {CreateSemaphore (NULL, 1, 1, "singleApp"); // Create the semaphore if (GetLastError () == ERROR_ALREADY_EXISTS) // If the signal is present in an amount return 1; else / // If there is no Return 0;
}
Then compile the DLL file with the C compiler.
I am using the Borland's C command line tool to compile. Note that the Java load is used by the SingleApp name, so our DLL name is also the same name, it is SingleApp.dll.
Also note that the DLL is to be placed on the Java's class loader, such as the place specified by ClassPath.
4. Run the Java program
Java SingleApp
Then open a console window, run the Java program, automatically exit the virtual machine during the second run. Simple!