samples/deadlock/src/org/apidesign/deadlock/startuplock/CLIHandler.java
author Jaroslav Tulach <jtulach@netbeans.org>
Sat, 14 Jun 2008 09:54:31 +0200
changeset 106 a773f1bc5ba1
child 133 50bf1b976c0d
permissions -rw-r--r--
Racecondition tests
     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 
     9 public final class CLIHandler {
    10     // BEGIN: cli.vision
    11     public static int start(File lockFile) throws IOException {
    12         if (lockFile.exists ()) {
    13             // read the port number and connect to it
    14             int alive = readPortNumber(lockFile);
    15             if (alive != -1) {
    16                 // exit
    17                 return alive;
    18             }
    19         }
    20         // otherwise try to create the file yourself
    21         lockFile.createNewFile();
    22         DataOutputStream os = new DataOutputStream(new FileOutputStream(lockFile));
    23         ServerSocket server = new ServerSocket();
    24         int p = server.getLocalPort();
    25         os.writeInt(p);
    26         
    27         return p;
    28     }
    29     // END: cli.vision
    30 
    31     private static int readPortNumber(File lockFile) throws IOException {
    32         return -1;
    33     }
    34 }