It is easy to implement a control application in C to run a process instance, which is also very good in C #, but the number of instances that want to control the program in Java is very suffering. The reason is because C and C # are implemented by the process mutual exclusion by registering the Windows registration, but Java is cross-platform, which cannot be implemented in this way for Windows.
Because there is very independent in Java, there are very few things that can be shared, so only things that can be shared between processes can only realize the mutual exclusion of the process. There are two things that can be used to achieve mutual exclusion. First, the Socket port, one is the file lock. Because the use of sockets may exist in the port occupied, and this type of network port is originally tight resources to achieve mutual exclusion. So we use the second thing here to implement the process mutual exclusion: file lock.
With a file lock to achieve mutual exclusion, there is also a benefit that controls the number of process instances, such as control only three instances or four instances, rather than running only as a general program.
In order to implement the number of process instances in the file lock, I wrote an instancecount class here. The method is as follows:
INT count = instancecount.getInstance (). getCount (); // Get the number of process instances currently already running in this program.
Then you can control the number of instances based on this count, such as:
IF (count> 3) system.exit (0);
However, here should pay attention to a question, that is, the Java application consists of a plurality of Class files. If there are multiple copies of these Class files in the system, I think they are different Application, that is, only the same class file is started. The process is as different from the same application. This definition can modify my code if everyone is not accepted, in line with your own definition.
This type also needs to use another class PATH. This class has introduced in another article I have written in another article "The absolute path of class of class files":
Http://blog.9cbs.net/youyue/archive/2005/03/22/32647.aspx
Such source code is as follows:
* Create Date 2005-1-26 * * Todo To change the template for this generated file, go to * Window - Preference - Java - Code Style - Code Template * / package mytools;
import java.io.File; import java.io.FilenameFilter; import java.io.IOException; import java.io.RandomAccessFile; import java.nio.channels.FileChannel; import java.nio.channels.FileLock;
/ ** * This class can be used to get the number of instances of the Java program. The example here refers to the process instance generated by the same Java program, and the so-called "same" refers to a Class file or JAR file, * If you copy these files to other locations, re-run the instance, no An instance of the same Java program that belongs to this class. * * @Author by month * @version 2005-02-01 * / public class instancecount {private int count = 0;
Private static instancecount theinstance = NULL;
PRIVATE FILEPATH = NULL;
Private file tempfile = null; // Used to identify the temporary file of this example private filechannel filechannel = null;
PRIVATE FILELOCK FILELOCK = NULL;
Private randomaccessfile rafile = NULL;
Private instanceCount () throws ioException {// Private constructor ensures that this class cannot create an object with a New operator. String path = path.getpathfromclass (this.getClass ()); // Get the path of the Class file of the InstanceCount class this.FilePath = new file (this.FilePath.getParent (), " "); If (this.filepath.exists () && this.filepath.isDirectory ()) {// does already exist instth ();} else {this.filepath.mkdir ();} this.tempFile = File.createTempFile ("~ inst", ".tmp", this.filepath); // Create a temporary file this.rafile = new randomaccessfile (THISTEMPFILE, "RW"); this.tempfile = rafile. GetChannel (); // Get the filechannel object this.filelock = filechannel.trylock (); // to ensure the uniqueness of the process instance this.tempfile.deleteOxit (); if (this.filelock ! = null) {this.count ; // New instance generation, the total number of instances increase 1} else {throw new oException ();}}
Private void getCountandMax () {file [] filelist = this.filepath.listfiles (new filenamefilter () {// Gets a list of temporary files under instthMP directory Public Boolean Accept (File Dir, String Name) {// This filter is used here Grouting only the list of .TMP files Try {file tempfile = new file (dir, name); randomaccessfile = new randomaccessfile (TempFile, "RW"); FileChannel FileChannel = rafile.getChannel (); / / get the file objects FileChannel FileLock fileLock = null; if (! InstanceCount.this.tempFile = null && name.equals (InstanceCount.this.tempFile .getName ())) {} else {fileLock = fileChannel.tryLock (); } IF (Tempfile.isfile () && name.endswith (". TMP") && (filelock == null || filelock.isvalid () == false)) {rafile.close (); return true;} else {filelock .release (); rafile.close (); TempFile.delete (); // Delete the unlocked and file name incorrect files to Return false;}} catch (ooException e) {E.PrintStackTrace ();Return False;}}}); this.count = filelist.length;} / ** * Get the number of instances control objects. One process can get up to an instancecount object. * * @Return only InstanceCount objects * / public static InstanceCount getInstance () {if (InstanceCount.theInstance == null) {// ensure that only one instance of this class try {InstanceCount instCtrl = program in a new InstanceCount (); return Instctrl;} catch (ioException e) {return null; // Return null value}} else {return instancecount.theinstance;}}}
/ ** * Get the number of instances being running. * * @Return instance number. * / Public int getCount () {getcountandmax (); returnim
Protected void finalize () {THIS.FILOCK.RELEASE (); this.filechannel.close (); this.Rafile.close (); this.tempfile.delete (); this.filepath.delete ();} catch (OoException e) {}} public static void main (string [] args) {Try {InstanceCount IC = instancecount.getinstance (); system.out.println (ic.getcount ()); thread.sleep (5000);} Catch (Exception E) {E.PrintStackTrace ();}}}