好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

Java程序单实例运行的简单实现

需求

最近做了个java项目,功能完成后打包安装了,发现可以点开多个实例,因为桌面显示托盘,所以点一次就会出现一个托盘,并且系统也多了好几个javaw进程,这样的话就不能保证程序的健壮性了,所以需要做一个判断让程序只运行一个实例。

实现方式

Java没有提供这样的机制。从操作系统的观点来看,一个启动的Java Application仅仅是一个JVM的运行实例。运行相同Application的两个实例,仅仅是运行两个无关的JVM。

只有让多个运行实例之间有一个既定的通讯机制就可以保证只有一个实例运行。

因为要考虑平台无关,java程序的实例控制不应该使用系统的内核对象来完成,那么我们就必须找到其它的、可以独享的资源。实际上,一台机器无论是在什么操作系统上,网络端口都是独享的,也就是说基于网络端口这个独享的原理,我们可以很方便地让我们的Java程序实现在内存里面只有一个运行实例这个功能,而且这个功能的实现是与平台无关的。

使用端口号控制的方式,先创建端口,运行的时候再判断端口是否被占用来判断是否启动新实例。

文件锁的方式,这种方式的用法在于运行程序的时候将文件上锁,然后判断这个文件是否被锁进而来判断是否要运行一个新实例。

使用端口号+文件的方式,这种方式的用法在于启动的时候创建一个文件,关闭的时候删掉这个文件,当然仅仅这么一个操作不能起到上述要求的,如果非法关闭的话,文件还存在就不能满足要求,只能是再加上一个端口的控制,即当端口被占用并且文件存在的情况下就停止运行新实例,否则启动一个实例,经试验这种方式可以得到满足。

代码实现

第一种实现(端口控制)

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

//方案:使用java.net.ServerSocket

//问题:打开服务端口可能会受到防火墙的影响;可能和别的端口冲突。

import java.io.*;

import java.net.*;

public class OneInstance_2

{

     private static ServerSocket listenerSocket;

     public static void main(String[] args)

     {

         try

         {

             listenerSocket = new ServerSocket( 2004 );

             //At this point, no other socket may listen on port 2004.

         }

         catch (java.net.BindException e)

         {

             System.err.println( "A previous instance is already running...." );

             System.exit( 1 );

         }

         catch ( final IOException e)     // an unexpected exception occurred

         {

             System.exit( 1 );

         }

         // Do some work here.....

     }

}

第二种实现(文件锁)

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

/*方案:使用Java的加锁文件机制,idea相当简单,让运行实例通过java.nio.channels.FileLock获得一个"well-known"文件的互斥锁。*/

//存在的问题:平台相关

import java.io.*;

import java.nio.channels.*;

public class OneInstance_1 {

   public static void main(String[] args) throws Exception {

     FileLock lck = new FileOutputStream( "C:\\flagFile" ).getChannel().tryLock();        

     if (lck == null ) {

       System.out.println( "A previous instance is already running...." );

       System.exit( 1 );

     }

     System.out.println( "This is the first instance of this program..." );

     // Do some work here.....

   }

}

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

//方案3:使用File.createNewFile() and File.deleteOnExit()

//问题:文件可能因为某些原因不能被删除,即使利用Runtime.addShutdownHook()也有可能产生这种情况。

import java.io.*;

public class OneInstance_3

{

     public static void main(String[] args) throws Exception

     {

         File flagFile = new File( "C:\\flagFile" );

         if ( false == flagFile.createNewFile())

         {

             System.out.println( "A previous instance is already running...." );

             System.exit( 1 );

         }

         flagFile.deleteOnExit();

         System.out.println( "This is the first instance of this program..." );    // Do some work here.....

     }

}

第三种方式(端口+文件锁)

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

public static void main(String[] args) throws IOException

{

     //创建lock.java文件

     String filePath = new File( "IDRCallDll" ).getAbsolutePath().substring( 0 ,

             new File( "IDRCallDll" ).getAbsolutePath().lastIndexOf( "\\" ));

     File getFile = new File(filePath + "\\" + "lock.java" );

     System.out.println(getFile.getPath());

 

     //判断端口是否被占用

     boolean flag = isLoclePortUsing( 20520 );

     System.out.println(flag);

 

     //如果文件存在并且端口被占用则退出

     if (getFile.exists() && flag)

     {

 

         new MyTray().showDialog();

         System.exit( 0 );

     }

 

     try

     {

         Socket sock = new Socket( "127.0.0.1" , 20520 ); // 创建socket,连接20520端口

     }

     catch (Exception e)

     {

         System.out.println( "端口被占用!" );

     }

 

     final Class<?> clazz = (Class<?>) JavaCall. class ;

     final boolean isWindows = System.getProperty( "os.name" ).contains(

                                   "Windows" );

     final List<String> args1 = new ArrayList<String>();

     args1.add(isWindows ? "javaw" : "java" );

     args1.add( "-Xmx" + 128 + "M" );

     args1.add( "-cp" );

      args1.add(System.getProperty( "java.class.path" ));

     args1.add( "-Djava.library.path="

               + System.getProperty( "java.library.path" ));

     args1.add(clazz.getCanonicalName());

     // logger.info("start " + args1.toString());

     final ProcessBuilder pb = new ProcessBuilder(args1);

     pb.redirectErrorStream( true ); 

     try

     {

         /**

         * 读身份证信息程序

         */

 

         pb.start();

     }

     catch (Exception e)

     {

         // TODO Auto-generated catch block

         e.printStackTrace();

     } 

 

     RandomAccessFile r = new RandomAccessFile(

         filePath + "\\" + "lock.java" , "rws" );

     FileChannel temp = r.getChannel();

     FileLock fl = temp.lock();

}

 

/**

* 判断端口是否被占用

* @param port

* @return

*/

 

public static boolean isLoclePortUsing( int port)

{

     boolean flag = true ;

     try

     {

         flag = isPortUsing( "127.0.0.1" , port);

     }

     catch (Exception e)

     {

     }

     return flag;

}

 

public static boolean isPortUsing(String host, int port) throws UnknownHostException

{

     boolean flag = false ;

     InetAddress theAddress = InetAddress.getByName(host);

     System.out.println(theAddress);

 

     try

     {

         ServerSocket socket = new ServerSocket(port);

         flag = true ;

     }

     catch (IOException e)

     {

         System.out.println( "beizhanyong" );

     }

     return flag;

}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

原文链接:https://fanxiaobin.blog.csdn.net/article/details/51890322

查看更多关于Java程序单实例运行的简单实现的详细内容...

  阅读:16次