単一インスタンスの Java アプリケーションを実装するにはどうすればよいですか?

StackOverflow https://stackoverflow.com/questions/177189

  •  05-07-2019
  •  | 
  •  

質問

時々、msn、Windows Media Player などの多くのアプリケーションが単一インスタンス アプリケーションであるのを目にします (アプリケーションの実行中にユーザーが実行しても、新しいアプリケーション インスタンスは作成されません)。

C#では、私は使用します Mutex このクラスを作成しましたが、Java でこれを行う方法がわかりません。

役に立ちましたか?

解決

この記事を信じている場合、by:

  

最初のインスタンスを使用すると、localhostインターフェースで待機ソケットを開こうとします。ソケットを開くことができる場合、これが起動されるアプリケーションの最初のインスタンスであると想定されます。そうでない場合、このアプリケーションのインスタンスがすでに実行されていることが前提となります。新しいインスタンスは、既存のインスタンスに起動が試行されたことを通知してから終了する必要があります。既存のインスタンスは、通知を受け取った後に引き継ぎ、アクションを処理するリスナーにイベントを発生させます。

注: Ahe は、 InetAddress.getLocalHost()を使用すると、トリッキー:

  
      
  • 返されるアドレスはコンピューターがネットワークにアクセスできるかどうかに依存するため、DHCP環境では期待どおりに機能しません。   解決策は、 InetAddress.getByAddress(new byte [] {127、0、0、1}) ;
    との接続を開くことでした。   おそらく bug 4435662 に関連しています。
  •   
  • また、バグ4665037 が見つかりました。 getLocalHost :マシンのIPアドレスと実際の結果の比較: 127.0.0.1 を返します。
  

getLocalHost がLinuxでは 127.0.0.1 を返すが、Windowsでは返さないのは驚くべきことです。


または ManagementFactory オブジェクト。説明したように、こちら

  

getMonitoredVMs(int processPid)メソッドは、現在のアプリケーションPIDをパラメーターとして受け取り、コマンドラインから呼び出されるアプリケーション名をキャッチします。たとえば、アプリケーションは cから開始されました。 \ java \ app \ test.jar パスの場合、値変数は" c:\\ java \\ app \\ test.jar "です。このようにして、以下のコードの17行目でアプリケーション名だけをキャッチします。
  その後、JVMで同じ名前の別のプロセスを検索します。それが見つかり、アプリケーションPIDが異なる場合、それは2番目のアプリケーションインスタンスであることを意味します。

JNLPは SingleInstanceListener

他のヒント

mainメソッドで次のメソッドを使用します。これは私が見た中で最も単純で、最も堅牢で、邪魔にならない方法なので、共有したいと思いました。

private static boolean lockInstance(final String lockFile) {
    try {
        final File file = new File(lockFile);
        final RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
        final FileLock fileLock = randomAccessFile.getChannel().tryLock();
        if (fileLock != null) {
            Runtime.getRuntime().addShutdownHook(new Thread() {
                public void run() {
                    try {
                        fileLock.release();
                        randomAccessFile.close();
                        file.delete();
                    } catch (Exception e) {
                        log.error("Unable to remove lock file: " + lockFile, e);
                    }
                }
            });
            return true;
        }
    } catch (Exception e) {
        log.error("Unable to create and/or lock file: " + lockFile, e);
    }
    return false;
}

アプリの場合。 GUIがあり、JWSで起動し、 SingleInstanceService を使用します。 デモを参照してください。 (デモおよび)サンプルコードのSingleInstanceServiceの

はい、これは日食RCP日食シングルインスタンスアプリケーションにとって本当にまともな答えです 以下は私のコードです

application.java

if(!isFileshipAlreadyRunning()){
        MessageDialog.openError(display.getActiveShell(), "Fileship already running", "Another instance of this application is already running.  Exiting.");
        return IApplication.EXIT_OK;
    } 


private static boolean isFileshipAlreadyRunning() {
    // socket concept is shown at http://www.rbgrn.net/content/43-java-single-application-instance
    // but this one is really great
    try {
        final File file = new File("FileshipReserved.txt");
        final RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
        final FileLock fileLock = randomAccessFile.getChannel().tryLock();
        if (fileLock != null) {
            Runtime.getRuntime().addShutdownHook(new Thread() {
                public void run() {
                    try {
                        fileLock.release();
                        randomAccessFile.close();
                        file.delete();
                    } catch (Exception e) {
                        //log.error("Unable to remove lock file: " + lockFile, e);
                    }
                }
            });
            return true;
        }
    } catch (Exception e) {
       // log.error("Unable to create and/or lock file: " + lockFile, e);
    }
    return false;
}

これにはファイルロックを使用します(ユーザーのアプリデータディレクトリ内のマジックファイルの排他ロックを取得します)が、主に複数のインスタンスが実行されないようにすることに関心があります。

2番目のインスタンスにコマンドライン引数などを最初のインスタンスに渡そうとしている場合、localhostでソケット接続を使用すると、1石で2羽の鳥が殺されます。一般的なアルゴリズム:

  • 起動時に、localhostのポートXXXXでリスナーを開こうとします
  • 失敗した場合、ローカルホスト上のそのポートへのライターを開き、コマンドライン引数を送信してからシャットダウンします
  • それ以外の場合は、localhostのポートXXXXXでリッスンします。コマンドライン引数を受け取ったら、あたかもそのコマンドラインでアプリが起動されたかのように処理します。

解決策、少し漫画的な説明を見つけましたが、ほとんどの場合はまだ動作します。ものを作成する単純な古いロックファイルを使用しますが、まったく異なるビューで:

http://javalandscape.blogspot.com/ 2008/07 / single-instance-from-your-application.html

これは、ファイアウォール設定が厳しい場合の助けになると思います。

JUniqueライブラリを使用できます。単一インスタンスJavaアプリケーションの実行をサポートし、オープンソースです。

http://www.sauronsoftware.it/projects/junique/

  

JUniqueライブラリを使用して、ユーザーが同時に実行されるのを防ぐことができます   同じJavaアプリケーションのインスタンスをさらに増やします。

     

JUniqueは、すべての間で共有されるロックと通信チャネルを実装します   同じユーザーによって起動されたJVMインスタンス。

public static void main(String[] args) {
    String appId = "myapplicationid";
    boolean alreadyRunning;
    try {
        JUnique.acquireLock(appId, new MessageHandler() {
            public String handle(String message) {
                // A brand new argument received! Handle it!
                return null;
            }
        });
        alreadyRunning = false;
    } catch (AlreadyLockedException e) {
        alreadyRunning = true;
    }
    if (!alreadyRunning) {
        // Start sequence here
    } else {
        for (int i = 0; i < args.length; i++) {
            JUnique.sendMessage(appId, args[0]));
        }
    }
}

内部では、%USER_DATA%/。juniqueフォルダーにファイルロックを作成し、Javaアプリケーション間でメッセージを送受信できるようにする一意のappIdごとにランダムポートにサーバーソケットを作成します。

Windowsでは、 launch4j を使用できます。

J2SE 5.0 以降でサポートされる ManagementFactory クラス 詳細

しかし、今はJ2SE 1.4を使用しており、これを見つけました http://audiprimadhanty.wordpress.com/2008/06/30/ensuring-one-instance-of-application-running-at-one-time/ しかし、私は決してテストしません。あなたはそれについてどう思いますか?

Preferences APIを使用してみてください。プラットフォームに依存しません。

単一のマシンまたはネットワーク全体でのインスタンスの数を制限するより一般的な方法は、マルチキャストソケットを使用することです。

マルチキャストソケットを使用すると、アプリケーションの任意の量のインスタンスにメッセージをブロードキャストできます。その一部は、企業ネットワーク上の物理的に離れたマシン上にある場合があります。

このようにして、多くのタイプの構成を有効にして、次のようなものを制御できます

  • マシンごとに1つまたは多数のインスタンス
  • ネットワークごとに1つまたは多数のインスタンス(例:クライアントサイトでのインストールの制御)

Javaのマルチキャストサポートは、 MulticastSocket java.netパッケージによるものです。 DatagramSocket がメインツールです。

:MulticastSocketはデータパケットの配信を保証しないため、 JGroups 。 JGroupsはすべてのデータの配信をします。非常にシンプルなAPIを備えた単一のjarファイルです。

JGroupsはしばらく前から存在し、業界ではいくつかの印象的な使用法があります。たとえば、JBossのクラスター化メカニズムはクラスターのすべてのインスタンスにデータをブロードキャストします。

JGroupsを使用して、アプリのインスタンスの数を制限するには(マシンまたはネットワークで、たとえば、顧客が購入したライセンスの数に)概念的に非常に簡単です:

  • アプリケーションの起動時に、各インスタンスは「My Great App Group」などの名前付きグループに参加しようとします。 0、1、またはNメンバーを許可するようにこのグループを構成します
  • グループメンバー数が設定した数を超えている場合。アプリは起動を拒否する必要があります。

メモリマップファイルを開き、そのファイルが既に開いているかどうかを確認できます。既に開いている場合は、メインから戻ることができます。

その他の方法は、ロックファイルを使用することです(UNIXの標準的な方法)。もう1つの方法は、クリップボードに何かが既にあるかどうかを確認した後、mainが開始したときに何かをクリップボードに入れることです。

その他、待機モード(ServerSocket)でソケットを開くことができます。まず、ソケットへの接続を試みます。接続できない場合は、serversocketを開きます。接続すると、別のインスタンスがすでに実行されていることがわかります。

したがって、ほとんどすべてのシステムリソースを使用して、アプリが実行されていることを知ることができます。

BR、 〜A

そのためにソケットを使用しましたが、アプリケーションがクライアント側にあるかサーバー側にあるかによって、動作が少し異なります:

  • クライアント側:インスタンスが既に存在する場合(特定のポートでリッスンできない場合)、アプリケーションパラメーターを渡して終了します(前のインスタンスでいくつかのアクションを実行したい場合があります)。 / li>
  • サーバー側:インスタンスが既に存在する場合はメッセージを出力して終了し、存在しない場合はアプリケーションを起動します。
public class SingleInstance {
    public static final String LOCK = System.getProperty("user.home") + File.separator + "test.lock";
    public static final String PIPE = System.getProperty("user.home") + File.separator + "test.pipe";
    private static JFrame frame = null;

    public static void main(String[] args) {
        try {
            FileChannel lockChannel = new RandomAccessFile(LOCK, "rw").getChannel();
            FileLock flk = null; 
            try {
                flk = lockChannel.tryLock();
            } catch(Throwable t) {
                t.printStackTrace();
            }
            if (flk == null || !flk.isValid()) {
                System.out.println("alread running, leaving a message to pipe and quitting...");
                FileChannel pipeChannel = null;
                try {
                    pipeChannel = new RandomAccessFile(PIPE, "rw").getChannel();
                    MappedByteBuffer bb = pipeChannel.map(FileChannel.MapMode.READ_WRITE, 0, 1);
                    bb.put(0, (byte)1);
                    bb.force();
                } catch (Throwable t) {
                    t.printStackTrace();
                } finally {
                    if (pipeChannel != null) {
                        try {
                            pipeChannel.close();
                        } catch (Throwable t) {
                            t.printStackTrace();
                        }
                    } 
                }
                System.exit(0);
            }
            //We do not release the lock and close the channel here, 
            //  which will be done after the application crashes or closes normally. 
            SwingUtilities.invokeLater(
                new Runnable() {
                    public void run() {
                        createAndShowGUI();
                    }
                }
            );

            FileChannel pipeChannel = null;
            try {
                pipeChannel = new RandomAccessFile(PIPE, "rw").getChannel();
                MappedByteBuffer bb = pipeChannel.map(FileChannel.MapMode.READ_WRITE, 0, 1);
                while (true) {
                    byte b = bb.get(0);
                    if (b > 0) {
                        bb.put(0, (byte)0);
                        bb.force();
                        SwingUtilities.invokeLater(
                            new Runnable() {
                                public void run() {
                                    frame.setExtendedState(JFrame.NORMAL);
                                    frame.setAlwaysOnTop(true);
                                    frame.toFront();
                                    frame.setAlwaysOnTop(false);
                                }
                            }
                        );
                    }
                    Thread.sleep(1000);
                }
            } catch (Throwable t) {
                t.printStackTrace();
            } finally {
                if (pipeChannel != null) {
                    try {
                        pipeChannel.close();
                    } catch (Throwable t) {
                        t.printStackTrace();
                    } 
                } 
            }
        } catch(Throwable t) {
            t.printStackTrace();
        } 
    }

    public static void createAndShowGUI() {

        frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(800, 650);
        frame.getContentPane().add(new JLabel("MAIN WINDOW", 
                    SwingConstants.CENTER), BorderLayout.CENTER);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}

EDIT :このWatchServiceアプローチを使用する代わりに、シンプルな1秒のタイマースレッドを使用して、indicatorFile.exists()かどうかを確認できます。削除してから、アプリケーションをFront()に移動します。

編集:なぜこれがダウン投票されたのか知りたい。これは私が今まで見た中で最高の解決策です。例えば。別のアプリケーションが既にポートをリッスンしている場合、サーバーソケットアプローチは失敗します。

Microsoft Windows Sysinternalsをダウンロードするだけ TCPView (またはnetstatを使用) 、それを開始し、&quot; State&quot;でソートし、&quot; LISTENING&quot;と言う行ブロックを探し、リモートアドレスがコンピューターの名前を示すものを選択し、そのポートをnew-Socket()-solutionに入れます。私の実装では、毎回障害が発生する可能性があります。そして、それはアプローチのまさに基盤であるため、論理的です。または、これを実装する方法に関して何が得られないのですか?

これについて、私が間違っているかどうか、どのように間違っているかを教えてください!

可能な限り反証するようお願いしていますが、私の見解では、開発者は実稼働コードで約60000のケースのうち少なくとも1つで失敗するアプローチを使用するように勧められています。このビューが正しい場合、この問題のない提示されたソリューションがそのコード量に対してダウン票され、批判されることは絶対にありえません

ソケットアプローチの欠点の比較:

  • 間違った宝くじチケット(ポート番号)が選択されると失敗します。
  • マルチユーザー環境で失敗する:アプリケーションを同時に実行できるユーザーは1人だけです。 (ユーザーツリーにファイルを作成するには、私のアプローチを少し変更する必要がありますが、それは簡単です。)
  • ファイアウォールルールが厳しすぎると失敗します。
  • 疑わしいユーザー(私は実際に会ったことがあります)に、テキストエディターがサーバーソケットを要求しているとき、あなたは何をしているのだろうと思います。

新しいインスタンスから既存のインスタンスへのJava通信の問題をすべてのシステムで機能する方法で解決する方法について、いいアイデアがありました。それで、私はこのクラスを約2時間でホイップしました。チャームのように機能します:D

これは Robert のファイルロックアプローチ(このページでも同様)に基づいています。既に実行中のインスタンスに別のインスタンスが開始しようとした(しかし、開始しなかった)ことを伝えるために...ファイルが作成され、すぐに削除され、最初のインスタンスはWatchServiceを使用してこのフォルダーコンテンツの変更を検出します。問題がどれほど根本的なものであるかを考えると、明らかにこれが新しいアイデアだとは信じられません。

これは、ファイルを削除せずに作成に簡単に変更できます。その後、適切なインスタンスが評価できる情報をそこに入れることができます。コマンドライン引数-そして適切なインスタンスが削除を実行できます。個人的には、いつアプリケーションのウィンドウを復元して前面に送信するかを知る必要がありました。

使用例:

public static void main(final String[] args) {

    // ENSURE SINGLE INSTANCE
    if (!SingleInstanceChecker.INSTANCE.isOnlyInstance(Main::otherInstanceTriedToLaunch, false)) {
        System.exit(0);
    }

    // launch rest of application here
    System.out.println("Application starts properly because it's the only instance.");
}

private static void otherInstanceTriedToLaunch() {
    // Restore your application window and bring it to front.
    // But make sure your situation is apt: This method could be called at *any* time.
    System.err.println("Deiconified because other instance tried to start.");
}

クラスは次のとおりです。

package yourpackagehere;

import javax.swing.*;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileLock;
import java.nio.file.*;




/**
 * SingleInstanceChecker v[(2), 2016-04-22 08:00 UTC] by dreamspace-president.com
 * <p>
 * (file lock single instance solution by Robert https://stackoverflow.com/a/2002948/3500521)
 */
public enum SingleInstanceChecker {

    INSTANCE; // HAHA! The CONFUSION!


    final public static int POLLINTERVAL = 1000;
    final public static File LOCKFILE = new File("SINGLE_INSTANCE_LOCKFILE");
    final public static File DETECTFILE = new File("EXTRA_INSTANCE_DETECTFILE");


    private boolean hasBeenUsedAlready = false;


    private WatchService watchService = null;
    private RandomAccessFile randomAccessFileForLock = null;
    private FileLock fileLock = null;


    /**
     * CAN ONLY BE CALLED ONCE.
     * <p>
     * Assumes that the program will close if FALSE is returned: The other-instance-tries-to-launch listener is not
     * installed in that case.
     * <p>
     * Checks if another instance is already running (temp file lock / shutdownhook). Depending on the accessibility of
     * the temp file the return value will be true or false. This approach even works even if the virtual machine
     * process gets killed. On the next run, the program can even detect if it has shut down irregularly, because then
     * the file will still exist. (Thanks to Robert https://stackoverflow.com/a/2002948/3500521 for that solution!)
     * <p>
     * Additionally, the method checks if another instance tries to start. In a crappy way, because as awesome as Java
     * is, it lacks some fundamental features. Don't worry, it has only been 25 years, it'll sure come eventually.
     *
     * @param codeToRunIfOtherInstanceTriesToStart Can be null. If not null and another instance tries to start (which
     *                                             changes the detect-file), the code will be executed. Could be used to
     *                                             bring the current (=old=only) instance to front. If null, then the
     *                                             watcher will not be installed at all, nor will the trigger file be
     *                                             created. (Null means that you just don't want to make use of this
     *                                             half of the class' purpose, but then you would be better advised to
     *                                             just use the 24 line method by Robert.)
     *                                             <p>
     *                                             BE CAREFUL with the code: It will potentially be called until the
     *                                             very last moment of the program's existence, so if you e.g. have a
     *                                             shutdown procedure or a window that would be brought to front, check
     *                                             if the procedure has not been triggered yet or if the window still
     *                                             exists / hasn't been disposed of yet. Or edit this class to be more
     *                                             comfortable. This would e.g. allow you to remove some crappy
     *                                             comments. Attribution would be nice, though.
     * @param executeOnAWTEventDispatchThread      Convenience function. If false, the code will just be executed. If
     *                                             true, it will be detected if we're currently on that thread. If so,
     *                                             the code will just be executed. If not so, the code will be run via
     *                                             SwingUtilities.invokeLater().
     * @return if this is the only instance
     */
    public boolean isOnlyInstance(final Runnable codeToRunIfOtherInstanceTriesToStart, final boolean executeOnAWTEventDispatchThread) {

        if (hasBeenUsedAlready) {
            throw new IllegalStateException("This class/method can only be used once, which kinda makes sense if you think about it.");
        }
        hasBeenUsedAlready = true;

        final boolean ret = canLockFileBeCreatedAndLocked();

        if (codeToRunIfOtherInstanceTriesToStart != null) {
            if (ret) {
                // Only if this is the only instance, it makes sense to install a watcher for additional instances.
                installOtherInstanceLaunchAttemptWatcher(codeToRunIfOtherInstanceTriesToStart, executeOnAWTEventDispatchThread);
            } else {
                // Only if this is NOT the only instance, it makes sense to create&delete the trigger file that will effect notification of the other instance.
                //
                // Regarding "codeToRunIfOtherInstanceTriesToStart != null":
                // While creation/deletion of the file concerns THE OTHER instance of the program,
                // making it dependent on the call made in THIS instance makes sense
                // because the code executed is probably the same.
                createAndDeleteOtherInstanceWatcherTriggerFile();
            }
        }

        optionallyInstallShutdownHookThatCleansEverythingUp();

        return ret;
    }


    private void createAndDeleteOtherInstanceWatcherTriggerFile() {

        try {
            final RandomAccessFile randomAccessFileForDetection = new RandomAccessFile(DETECTFILE, "rw");
            randomAccessFileForDetection.close();
            Files.deleteIfExists(DETECTFILE.toPath()); // File is created and then instantly deleted. Not a problem for the WatchService :)
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private boolean canLockFileBeCreatedAndLocked() {

        try {
            randomAccessFileForLock = new RandomAccessFile(LOCKFILE, "rw");
            fileLock = randomAccessFileForLock.getChannel().tryLock();
            return fileLock != null;
        } catch (Exception e) {
            return false;
        }
    }


    private void installOtherInstanceLaunchAttemptWatcher(final Runnable codeToRunIfOtherInstanceTriesToStart, final boolean executeOnAWTEventDispatchThread) {

        // PREPARE WATCHSERVICE AND STUFF
        try {
            watchService = FileSystems.getDefault().newWatchService();
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }
        final File appFolder = new File("").getAbsoluteFile(); // points to current folder
        final Path appFolderWatchable = appFolder.toPath();


        // REGISTER CURRENT FOLDER FOR WATCHING FOR FILE DELETIONS
        try {
            appFolderWatchable.register(watchService, StandardWatchEventKinds.ENTRY_DELETE);
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }


        // INSTALL WATCHER THAT LOOKS IF OUR detectFile SHOWS UP IN THE DIRECTORY CHANGES. IF THERE'S A CHANGE, ANOTHER INSTANCE TRIED TO START, SO NOTIFY THE CURRENT ONE OF THAT.
        final Thread t = new Thread(() -> watchForDirectoryChangesOnExtraThread(codeToRunIfOtherInstanceTriesToStart, executeOnAWTEventDispatchThread));
        t.setDaemon(true);
        t.setName("directory content change watcher");
        t.start();
    }


    private void optionallyInstallShutdownHookThatCleansEverythingUp() {

        if (fileLock == null && randomAccessFileForLock == null && watchService == null) {
            return;
        }

        final Thread shutdownHookThread = new Thread(() -> {
            try {
                if (fileLock != null) {
                    fileLock.release();
                }
                if (randomAccessFileForLock != null) {
                    randomAccessFileForLock.close();
                }
                Files.deleteIfExists(LOCKFILE.toPath());
            } catch (Exception ignore) {
            }
            if (watchService != null) {
                try {
                    watchService.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
        Runtime.getRuntime().addShutdownHook(shutdownHookThread);
    }


    private void watchForDirectoryChangesOnExtraThread(final Runnable codeToRunIfOtherInstanceTriesToStart, final boolean executeOnAWTEventDispatchThread) {

        while (true) { // To eternity and beyond! Until the universe shuts down. (Should be a volatile boolean, but this class only has absolutely required features.)

            try {
                Thread.sleep(POLLINTERVAL);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }


            final WatchKey wk;
            try {
                wk = watchService.poll();
            } catch (ClosedWatchServiceException e) {
                // This situation would be normal if the watcher has been closed, but our application never does that.
                e.printStackTrace();
                return;
            }

            if (wk == null || !wk.isValid()) {
                continue;
            }


            for (WatchEvent<?> we : wk.pollEvents()) {

                final WatchEvent.Kind<?> kind = we.kind();
                if (kind == StandardWatchEventKinds.OVERFLOW) {
                    System.err.println("OVERFLOW of directory change events!");
                    continue;
                }


                final WatchEvent<Path> watchEvent = (WatchEvent<Path>) we;
                final File file = watchEvent.context().toFile();


                if (file.equals(DETECTFILE)) {

                    if (!executeOnAWTEventDispatchThread || SwingUtilities.isEventDispatchThread()) {
                        codeToRunIfOtherInstanceTriesToStart.run();
                    } else {
                        SwingUtilities.invokeLater(codeToRunIfOtherInstanceTriesToStart);
                    }

                    break;

                } else {
                    System.err.println("THIS IS THE FILE THAT WAS DELETED: " + file);
                }

            }

            wk.reset();
        }
    }

}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top