How can I limit a Java application to a single instance when I start it up?

Question:

I have a (java application index.java ) if the run sail for their different JFrame or JDialog without problems, etc.

My doubt / question / query is: is there any method to not allow opening during the process of index.java another index.java ? And in case of trying to reopen it (if it is open) show a message: "It is in use".

I hope I have explained myself.

Code:

public class Index extends javax.swing.JFrame {
    public Index() {
        initComponents();
        //Fondo del JFrame en color gris.
        getContentPane().setBackground(Color.gray);
        //Código para confirmar el cierre de la ventana principal.
        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            @Override
            public void windowClosing(java.awt.event.WindowEvent evt){
                if (JOptionPane.showConfirmDialog(rootPane, "¿Desea salir de la aplicación?", "Salir de la aplicación",
                    JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
                    System.exit(0);
            }
        });

        //Situamos el JDialog en el centro de la pantalla.
        setLocationRelativeTo(null);
        //No redimensionable.
        setResizable(false);
    }

    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Index.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Index.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Index.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Index.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Index().setVisible(true);
            }
        });
    }
}

Answer:

Not directly on the java side, if the instances run on two different virtual machines. However you can fix the issue with a lock file.

in the main method you start with:

// deberías definir la ruta de tu lockfile en una forma que siempre se guarda en el mismo lugar en el misma sistema
File lock = new File("ruta/a/mi/lockfile");
if (lock.createNewFile()){
    lock.deleteOnExit();
    //lanza tu applicación
} else {
    System.out.println("Está en uso.")
    System.exit();
}
Scroll to Top