samples/deadlock/src/org/apidesign/deadlock/startuplock/CLIHandlerBlocking.java
author Jaroslav Tulach <jtulach@netbeans.org>
Sat, 14 Jun 2008 09:58:11 +0200
changeset 154 0fd5e9c500b9
parent 153 b5cbb797ec0a
permissions -rw-r--r--
Merge: Geertjan's changs up to 2000
     1 package org.apidesign.deadlock.startuplock;
     2 
     3 import java.io.DataOutputStream;
     4 import java.io.File;
     5 import java.io.FileOutputStream;
     6 import java.io.IOException;
     7 import java.net.ServerSocket;
     8 import java.util.logging.Level;
     9 import java.util.logging.Logger;
    10 
    11 public final class CLIHandlerBlocking {
    12     // BEGIN: cli.real
    13     public static int start(File lockFile) throws IOException {
    14         enterState(10);
    15         if (lockFile.exists ()) {
    16             // read the port number and connect to it
    17             enterState(11);
    18             int alive = readPortNumber(lockFile);
    19             if (alive != -1) {
    20                 // exit
    21                 return alive;
    22             }
    23         }
    24         // otherwise try to create the file yourself
    25         enterState(20);
    26         lockFile.createNewFile();
    27         DataOutputStream os = new DataOutputStream(
    28             new FileOutputStream(lockFile)
    29         );
    30         ServerSocket server = new ServerSocket();
    31         enterState(21);
    32         int p = server.getLocalPort();
    33         enterState(22);
    34         os.writeInt(p);
    35         enterState(23);
    36         
    37         return p;
    38     }
    39     // END: cli.real
    40 
    41     private static Logger LOG = Logger.getLogger(CLIHandlerBlocking.class.getName());
    42     private static void enterState(int state) {
    43         LOG.log(Level.FINEST, "enterState {0}", state);
    44     }
    45 
    46     private static int readPortNumber(File lockFile) throws IOException {
    47         return -1;
    48     }
    49 }