samples/deadlock/src/org/apidesign/deadlock/startuplock/CLIHandlerBlocking.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
jtulach@106
     1
package org.apidesign.deadlock.startuplock;
jtulach@106
     2
jtulach@106
     3
import java.io.DataOutputStream;
jtulach@106
     4
import java.io.File;
jtulach@106
     5
import java.io.FileOutputStream;
jtulach@106
     6
import java.io.IOException;
jtulach@106
     7
import java.net.ServerSocket;
jtulach@106
     8
import java.util.logging.Level;
jtulach@106
     9
import java.util.logging.Logger;
jtulach@106
    10
jtulach@106
    11
public final class CLIHandlerBlocking {
jtulach@106
    12
    // BEGIN: cli.real
jtulach@106
    13
    public static int start(File lockFile) throws IOException {
jtulach@106
    14
        enterState(10);
jtulach@106
    15
        if (lockFile.exists ()) {
jtulach@106
    16
            // read the port number and connect to it
jtulach@106
    17
            enterState(11);
jtulach@106
    18
            int alive = readPortNumber(lockFile);
jtulach@106
    19
            if (alive != -1) {
jtulach@106
    20
                // exit
jtulach@106
    21
                return alive;
jtulach@106
    22
            }
jtulach@106
    23
        }
jtulach@106
    24
        // otherwise try to create the file yourself
jtulach@106
    25
        enterState(20);
jtulach@106
    26
        lockFile.createNewFile();
jtulach@106
    27
        DataOutputStream os = new DataOutputStream(new FileOutputStream(lockFile));
jtulach@106
    28
        ServerSocket server = new ServerSocket();
jtulach@106
    29
        enterState(21);
jtulach@106
    30
        int p = server.getLocalPort();
jtulach@106
    31
        enterState(22);
jtulach@106
    32
        os.writeInt(p);
jtulach@106
    33
        enterState(23);
jtulach@106
    34
        
jtulach@106
    35
        return p;
jtulach@106
    36
    }
jtulach@106
    37
    // END: cli.real
jtulach@106
    38
jtulach@106
    39
    private static Logger LOG = Logger.getLogger(CLIHandlerBlocking.class.getName());
jtulach@106
    40
    private static void enterState(int state) {
jtulach@106
    41
        LOG.log(Level.FINEST, "enterState {0}", state);
jtulach@106
    42
    }
jtulach@106
    43
jtulach@106
    44
    private static int readPortNumber(File lockFile) throws IOException {
jtulach@106
    45
        return -1;
jtulach@106
    46
    }
jtulach@106
    47
}