Determine if only one instance is running: Difference between revisions

→‎{{header|Java}}: Fixed this example so it now compiles and runs properly.
(Found incorrectness.)
(→‎{{header|Java}}: Fixed this example so it now compiles and runs properly.)
Line 540:
 
=={{header|Java}}==
<lang java>import java.io.IOExeceptionIOException;
{{incorrect|Java|Doesn't compile.}}
<lang java>import java.io.IOExeception;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.UnknownHostException;
{
 
public class SingletonApp
{
private static final int PORT = 1234565000; // random large port number
private static ServerSocket s;
 
// static initializer
static {
try {
s = new ServerSocket(PORT, 10, InetAddress.getLocalHost());
} catch (UnknownHostException e) {
// shouldn't happen for localhost
} catch (IOException e) {
// port taken, so app is already running
System.out.print("Application is already running,");
System.out.println(" so terminating this instance.");
System.exit(0);
}
}
 
public static void main(String[] args) {
// static initializer
System.out.print("OK, only this instance is running");
{
System.out.println(" but will terminate in 10 seconds.");
try {
try {
s = new ServerSocket(PORT, 10, InetAddress.getLocalHost());
Thread.sleep(10000);
} catch (UnknownHostException e) {
if (s != null && !s.isClosed()) s.close();
// shouldn't happen for localhost
} catch (IOExceptionException e) {
System.err.println(e);
// port taken, so app is already running
}
System.exit(0);
}
}
}
// main() and rest of application...
}</lang>
 
9,476

edits