Example usage for java.lang Thread interrupted

List of usage examples for java.lang Thread interrupted

Introduction

In this page you can find the example usage for java.lang Thread interrupted.

Prototype

public static boolean interrupted() 

Source Link

Document

Tests whether the current thread has been interrupted.

Usage

From source file:org.covito.kit.cache.CacheTest.java

@Test
@Ignore/*from  w w  w  .  jav  a 2 s . c  o m*/
public void testAutoRefresh() {

    System.out.println(CacheManager.getCacheNames());

    final Cache<String, String> autoRefresh = CacheManager.getCache("autoRefresh");

    new Thread(new Runnable() {
        @Override
        public void run() {
            while (true) {
                System.out.println(autoRefresh.get("A"));
                ;
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }).start();
    ;
    Thread.interrupted();
}

From source file:interactivespaces.util.sampling.SampledDataSequencePlayer.java

/**
 * Play the frames in sequence.//from w w w  .j  a  v  a  2  s  . c  om
 *
 * @throws InterruptedException
 *           the player has been interrupted
 */
private void play() throws InterruptedException {

    List<SampledDataFrame> frames = sequence.getFrames();
    int maxFrames = frames.size() - 1;

    while (!Thread.interrupted()) {
        log.info("Starting playback of sampled data");
        SampledDataFrame currentFrame = frames.get(0);
        int[] samples = currentFrame.getSamples();
        sender.sendSampledData(currentFrame.getSource(), Arrays.copyOf(samples, samples.length));
        SampledDataFrame previousFrame;
        for (int frame = 1; !Thread.interrupted() && frame < maxFrames; frame++) {
            previousFrame = currentFrame;
            currentFrame = frames.get(frame);

            long delay = currentFrame.getTimestamp() - previousFrame.getTimestamp();
            if (delay > 0) {
                Thread.sleep(delay);
            }

            samples = currentFrame.getSamples();
            sender.sendSampledData(currentFrame.getSource(), Arrays.copyOf(samples, samples.length));
        }
        log.info("Ending playback of sampled data");
    }
}

From source file:info.sugoiapps.xoserver.XOverServer.java

/**
 * The main background task.//from   ww  w . j a v  a  2  s  .c o m
 * Accept connection from the server socket and read incoming messages.
 * Pass messages to mouse event handler.
 */
private void listen() {
    Socket socket = null;
    InputStream in = null;
    publish(CONNECTED_MESSAGE + PORT);
    System.out.println("about to enter server loop");
    while (!Thread.interrupted()) { //!Thread.interrupted()
        try {
            socket = server.accept(); // stop is clicked, this is still waiting for incoming connections, 
                                      // therefore once the server is closed, it will produce an error
                                      //socket.setKeepAlive(false);
            System.out.println("started accepting from socket");
        } catch (IOException ex) {
            serverClosedMessage(ex);
            break;
        }

        try {
            in = socket.getInputStream();
            InputStreamReader isr = new InputStreamReader(in);
            BufferedReader br = new BufferedReader(isr);
            String line = null;
            while ((line = br.readLine()) != null) {
                if (isCancelled()) {
                    in.close();
                    isr.close();
                    br.close();
                    socket.close();
                    break;
                }
                if (!addressReceived && isValidAddress(line)) {
                    System.out.println("address check entered");
                    addressReceived = true;
                    hostAddress = line;
                    startFileClient();
                } else {
                    imitateMouse(line);
                }
            }
        } catch (IOException ex) {
            ex.printStackTrace();
            serverClosedMessage(ex);
        }
    }
}

From source file:disko.flow.analyzers.socket.SocketReceiver.java

private Message readMessage(ServerSocket serverSocket) {
    while (true) {
        Socket clientSocket = null;
        ObjectInputStream in = null;
        try {//from   w  w  w .ja  va 2 s .  c o  m
            clientSocket = serverSocket.accept();
            in = new ObjectInputStream(clientSocket.getInputStream());
            Message message = null;
            try {
                message = (Message) in.readObject();
            } catch (IOException e) {
                log.error("Error reading object.", e);
                continue;
            } catch (ClassNotFoundException e) {
                log.error("Class not found.", e);
                continue;
            }
            // while (in.read() != -1);
            // if (in.available() > 0)
            // {
            // System.err.println("OOPS, MORE THAT ON SOCKET HASN'T BEEN
            // READ: " + in.available());
            // while (in.available() > 0)
            // in.read();
            // }
            return message;
        } catch (SocketTimeoutException ex) {
            if (Thread.interrupted())
                return null;
        } catch (InterruptedIOException e) // this doesn't really work, that's why we put an Socket timeout and we check for interruption
        {
            return null;
        } catch (IOException e) {
            log.error("Could not listen on port: " + port, e);
        } finally {
            if (in != null)
                try {
                    in.close();
                } catch (Throwable t) {
                    log.error("While closing receiver input.", t);
                }
            if (clientSocket != null)
                try {
                    clientSocket.close();
                } catch (Throwable t) {
                    log.error("While closing receiver socket.", t);
                }
        }
    }
}

From source file:org.aludratest.service.gui.web.selenium.httpproxy.RequestProcessorThread.java

/** The {@link Thread}'s worker method which processes the request. */
@Override//from  w ww  .  j  a v a  2s. c o  m
public void run() {
    LOGGER.debug("New request processor thread");

    // Create context and bind connection objects to the execution context
    HttpContext context = new BasicHttpContext(null);
    context.setAttribute(HTTP_IN_CONN, this.inconn);
    context.setAttribute(HTTP_OUT_CONN, this.outconn);

    // checking request's keep-alive attribute
    Boolean keepAliveObj = (Boolean) context.getAttribute(HTTP_CONN_KEEPALIVE);
    boolean keepAlive = (keepAliveObj != null && keepAliveObj.booleanValue());

    // handle in/out character transfer according to keep-alive setting
    try {
        while (!Thread.interrupted()) {
            if (!this.inconn.isOpen()) {
                this.outconn.close();
                break;
            }
            LOGGER.debug("Handling request");

            this.httpservice.handleRequest(this.inconn, context);

            if (!keepAlive) {
                this.outconn.close();
                this.inconn.close();
                LOGGER.debug("Finishing request");
                break;
            }
        }
    } catch (ConnectionClosedException ex) {
        if (keepAlive && owner.isRunning()) {
            LOGGER.error("Client closed connection");
        } else {
            LOGGER.debug("Client closed connection");
        }
    } catch (IOException ex) {
        LOGGER.error("I/O error: " + ex.getMessage());
    } catch (HttpException ex) {
        LOGGER.error("Unrecoverable HTTP protocol violation: " + ex.getMessage());
    } finally {
        try {
            this.inconn.shutdown();
        } catch (IOException ignore) {
            // ignore possible exceptions
        }
        try {
            this.outconn.shutdown();
        } catch (IOException ignore) {
            // ignore possible exceptions
        }
        LOGGER.debug("Finished connection thread");
    }
}

From source file:org.apache.hadoop.hdfs.server.datanode.DataBlockScannerSet.java

public void run() {
    try {//from   w  ww .  ja v a 2  s . c  o m
        int currentNamespaceId = -1;
        boolean firstRun = true;
        while (datanode.shouldRun && !Thread.interrupted()) {
            datanode.updateAndReportThreadLiveness(BackgroundThread.BLOCK_SCANNER);

            // Sleep everytime except in the first interation.
            if (!firstRun) {
                try {
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("Sleep " + TIME_SLEEP_BETWEEN_SCAN + " ms before next round of scanning");
                    }
                    Thread.sleep(TIME_SLEEP_BETWEEN_SCAN);
                } catch (InterruptedException ex) {
                    // Interrupt itself again to set the interrupt status
                    blockScannerThread.interrupt();
                    continue;
                }
            } else {
                firstRun = false;
            }

            DataBlockScanner nsScanner = getNextNamespaceSliceScanner(currentNamespaceId);
            if (nsScanner == null) {
                // Possible if thread is interrupted
                continue;
            }
            currentNamespaceId = nsScanner.getNamespaceId();
            waitForUpgradeDone(currentNamespaceId);

            if (!datanode.isNamespaceAlive(currentNamespaceId)) {
                LOG.warn("Namespace: " + currentNamespaceId + " is not alive");
                // Remove in case NS service died abruptly without proper shutdown
                removeNamespace(currentNamespaceId);
                continue;
            }
            if (LOG.isDebugEnabled()) {
                LOG.debug("Start scan namespace " + currentNamespaceId);
            }
            nsScanner.scanNamespace();
            if (LOG.isDebugEnabled()) {
                LOG.debug("Finish scan namespace " + currentNamespaceId);
            }
        }
    } finally {
        LOG.info("DataBlockScannerSet exited...");
    }
}

From source file:org.micromanager.plugins.magellan.surfacesandregions.SurfaceInterpolatorSimple.java

protected void interpolateSurface(LinkedList<Point3d> points) throws InterruptedException {

    double pixSize = Magellan.getCore().getPixelSizeUm();
    //provide interpolator with current list of data points
    Point_dt triangulationPoints[] = new Point_dt[points.size()];
    for (int i = 0; i < points.size(); i++) {
        triangulationPoints[i] = new Point_dt(points.get(i).x, points.get(i).y, points.get(i).z);
    }//  www. j a  v a 2 s  .  c o  m
    Delaunay_Triangulation dTri = new Delaunay_Triangulation(triangulationPoints);

    int maxPixelDimension = (int) (Math.max(boundXMax_ - boundXMin_, boundYMax_ - boundYMin_) / pixSize);
    //Start with at least 20 interp points and go smaller and smaller until every pixel interped?
    int pixelsPerInterpPoint = 1;
    while (maxPixelDimension / (pixelsPerInterpPoint + 1) > 20) {
        pixelsPerInterpPoint *= 2;
    }
    if (Thread.interrupted()) {
        throw new InterruptedException();
    }

    while (pixelsPerInterpPoint >= MIN_PIXELS_PER_INTERP_POINT) {
        int numInterpPointsX = (int) (((boundXMax_ - boundXMin_) / pixSize) / pixelsPerInterpPoint);
        int numInterpPointsY = (int) (((boundYMax_ - boundYMin_) / pixSize) / pixelsPerInterpPoint);
        double dx = (boundXMax_ - boundXMin_) / (numInterpPointsX - 1);
        double dy = (boundYMax_ - boundYMin_) / (numInterpPointsY - 1);

        float[][] interpVals = new float[numInterpPointsY][numInterpPointsX];
        float[][] interpNormals = new float[numInterpPointsY][numInterpPointsX];
        boolean[][] interpDefined = new boolean[numInterpPointsY][numInterpPointsX];
        for (int yInd = 0; yInd < interpVals.length; yInd++) {
            for (int xInd = 0; xInd < interpVals[0].length; xInd++) {
                if (Thread.interrupted()) {
                    throw new InterruptedException();
                }
                double xVal = boundXMin_ + dx * xInd;
                double yVal = boundYMin_ + dy * yInd;
                boolean inHull = convexHullRegion_
                        .checkPoint(new Vector2D(xVal, yVal)) == Region.Location.INSIDE;
                if (inHull) {
                    Triangle_dt tri = dTri.find(new Point_dt(xVal, yVal));
                    //convert to apache commons coordinates to make a plane
                    Vector3D v1 = new Vector3D(tri.p1().x(), tri.p1().y(), tri.p1().z());
                    Vector3D v2 = new Vector3D(tri.p2().x(), tri.p2().y(), tri.p2().z());
                    Vector3D v3 = new Vector3D(tri.p3().x(), tri.p3().y(), tri.p3().z());
                    Plane plane = new Plane(v1, v2, v3, TOLERANCE);
                    //intersetion of vertical line at these x+y values with plane gives point in plane
                    Vector3D pointInPlane = plane.intersection(
                            new Line(new Vector3D(xVal, yVal, 0), new Vector3D(xVal, yVal, 1), TOLERANCE));
                    float zVal = (float) pointInPlane.getZ();
                    interpVals[yInd][xInd] = zVal;
                    float angle = (float) (Vector3D.angle(plane.getNormal(), new Vector3D(0, 0, 1)) / Math.PI
                            * 180.0);
                    interpNormals[yInd][xInd] = angle;
                    interpDefined[yInd][xInd] = true;
                } else {
                    interpDefined[yInd][xInd] = false;
                }
            }
        }
        if (Thread.interrupted()) {
            throw new InterruptedException();
        }
        synchronized (interpolationLock_) {
            currentInterpolation_ = new SingleResolutionInterpolation(pixelsPerInterpPoint, interpDefined,
                    interpVals, interpNormals, boundXMin_, boundXMax_, boundYMin_, boundYMax_,
                    convexHullRegion_, convexHullVertices_, getPoints());
            interpolationLock_.notifyAll();
        }
        //         System.gc();
        pixelsPerInterpPoint /= 2;
    }
}

From source file:org.jenkinsci.plugins.mber.LoggingOutputStream.java

private void log(int length) throws IOException {
    // Users may arbitrarily stop a job while files are being transfered.
    // So we need to peridically check if the job's been canceled.
    if (Thread.interrupted()) {
        IOUtils.closeQuietly(this);
        throw new LoggingInterruptedException("Build was canceled.");
    }/* w w  w.j  a  v a 2 s  .c om*/
    this.bytesWritten += length;
}

From source file:httpscheduler.GenericRequestListenerThread.java

@Override
public void run() {
    System.out.println("Listening on port " + this.serversocket.getLocalPort());
    ArrayList<String> workerList = new ArrayList<>();

    // Read list of workers from configuration file
    try (BufferedReader br = new BufferedReader(new FileReader("./config/workers.conf"))) {
        for (String line; (line = br.readLine()) != null;) {
            workerList.add(line);//from  www. j a  va  2  s. co m
        }
    } catch (FileNotFoundException ex) {
        Logger.getLogger(GenericRequestListenerThread.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(GenericRequestListenerThread.class.getName()).log(Level.SEVERE, null, ex);
    }

    // Initialize worker manager
    try {
        WorkerManager.useWorkerList(workerList);
    } catch (Exception ex) {
        Logger.getLogger(GenericRequestListenerThread.class.getName()).log(Level.SEVERE, null, ex);
        System.exit(-1);
    }
    //WorkerManager.printWorkerMap();

    Thread workerStatusThread = new UpdateWorkerStatusThread();
    workerStatusThread.start();
    System.out.println("ready for connections");
    while (!Thread.interrupted()) {
        try {
            // Set up HTTP connection
            Socket socket = this.serversocket.accept();
            HttpServerConnection conn = this.connFactory.createConnection(socket);

            // Initialize the pool
            Thread connectionHandler = new ConnectionHandlerThread(this.httpService, conn);
            connectionHandler.setDaemon(true);
            connectionHandlerExecutor.execute(connectionHandler);
        } catch (InterruptedIOException ex) {
            break;
        } catch (IOException e) {
            System.err.println("I/O error initialising connection thread: " + e.getMessage());
            break;
        }
    }
    // when the listener is interupted shutdown the pool
    // and wait for any Connection Handler threads still running
    connectionHandlerExecutor.shutdown();
    while (!connectionHandlerExecutor.isTerminated()) {
    }

    System.out.println("Finished all connection handler threads");
}

From source file:httpscheduler.LateBindingRequestListenerThread.java

@Override
public void run() {
    System.out.println("Listening on port " + this.serversocket.getLocalPort());
    ArrayList<String> workerList = new ArrayList<>();

    // Read list of workers from configuration file
    try (BufferedReader br = new BufferedReader(new FileReader("./config/workers.conf"))) {
        for (String line; (line = br.readLine()) != null;) {
            workerList.add(line);/*from   www.  j  av a  2 s. com*/
        }
    } catch (FileNotFoundException ex) {
        Logger.getLogger(GenericRequestListenerThread.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(GenericRequestListenerThread.class.getName()).log(Level.SEVERE, null, ex);
    }

    // Initialize worker manager
    try {
        WorkerManager.useWorkerList(workerList);
    } catch (Exception ex) {
        Logger.getLogger(GenericRequestListenerThread.class.getName()).log(Level.SEVERE, null, ex);
        System.exit(-1);
    }
    WorkerManager.printWorkerMap();

    //jobMap.put(1, new String[1000]);
    Thread workerStatusThread = new UpdateWorkerStatusThread();
    workerStatusThread.start();
    System.out.println("ready for connections");
    while (!Thread.interrupted()) {
        try {
            // Set up HTTP connection
            Socket socket = this.serversocket.accept();
            System.out.println("Incoming connection from " + socket.getInetAddress());
            HttpServerConnection conn = this.connFactory.createConnection(socket);

            // Initialize the pool
            Thread connectionHandler = new ConnectionHandlerThread(this.httpService, conn);

            connectionHandler.setDaemon(false);
            connectionHandlerExecutor.execute(connectionHandler);
            System.out.println("\tConnection Handler Thread created");
        } catch (InterruptedIOException ex) {
            break;
        } catch (IOException e) {
            System.err.println("I/O error initialising connection thread: " + e.getMessage());
            break;
        }
    }
    // when the listener is interupted shutdown the pool
    // and wait for any Connection Handler threads still running
    connectionHandlerExecutor.shutdown();
    while (!connectionHandlerExecutor.isTerminated()) {
    }

    System.out.println("Finished all connection handler threads");
}