/** @param workTokDir Token directory (common for multiple nodes). */
    private void cleanupResources(File workTokDir) {
      RandomAccessFile lockFile = null;

      FileLock lock = null;

      try {
        lockFile = new RandomAccessFile(new File(workTokDir, LOCK_FILE_NAME), "rw");

        lock = lockFile.getChannel().lock();

        if (lock != null) processTokenDirectory(workTokDir);
        else if (log.isDebugEnabled())
          log.debug(
              "Token directory is being processed concurrently: " + workTokDir.getAbsolutePath());
      } catch (OverlappingFileLockException ignored) {
        if (log.isDebugEnabled())
          log.debug(
              "Token directory is being processed concurrently: " + workTokDir.getAbsolutePath());
      } catch (FileLockInterruptionException ignored) {
        Thread.currentThread().interrupt();
      } catch (IOException e) {
        U.error(log, "Failed to process directory: " + workTokDir.getAbsolutePath(), e);
      } finally {
        U.releaseQuiet(lock);
        U.closeQuiet(lockFile);
      }
    }
 /**
  * Marks the end of an I/O operation that might block indefinitely.
  *
  * <p>This method should be invoked in tandem with the {@link #begin begin} method, using a
  * <tt>try</tt>&nbsp;...&nbsp;<tt>finally</tt> block as shown <a href="#be">above</a>, in order to
  * implement asynchronous closing and interruption for this channel.
  *
  * @param completed <tt>true</tt> if, and only if, the I/O operation completed successfully, that
  *     is, had some effect that would be visible to the operation's invoker
  * @throws AsynchronousCloseException If the channel was asynchronously closed
  * @throws ClosedByInterruptException If the thread blocked in the I/O operation was interrupted
  */
 protected final void end(boolean completed) throws AsynchronousCloseException {
   blockedOn(null);
   Thread interrupted = this.interrupted;
   if (interrupted != null && interrupted == Thread.currentThread()) {
     interrupted = null;
     throw new ClosedByInterruptException();
   }
   if (!completed && !open) throw new AsynchronousCloseException();
 }
 /**
  * @param log Logger.
  * @param time Time.
  * @param msg Message.
  */
 private static void log0(@Nullable IgniteLogger log, long time, String msg) {
   if (log != null) {
     if (log.isDebugEnabled()) log.debug(msg);
     else log.warning(msg);
   } else
     X.println(
         String.format(
             "[%s][%s]%s",
             DEBUG_DATE_FMT.get().format(time), Thread.currentThread().getName(), msg));
 }
    /** {@inheritDoc} */
    @Override
    protected void body() throws InterruptedException, IgniteInterruptedCheckedException {
      if (log.isDebugEnabled()) log.debug("GC worker started.");

      File workTokDir = tokDir.getParentFile();

      assert workTokDir != null;

      boolean lastRunNeeded = true;

      while (true) {
        try {
          // Sleep only if not cancelled.
          if (lastRunNeeded) Thread.sleep(GC_FREQ);
        } catch (InterruptedException ignored) {
          // No-op.
        }

        if (log.isDebugEnabled()) log.debug("Starting GC iteration.");

        cleanupResources(workTokDir);

        // Process spaces created by this endpoint.
        if (log.isDebugEnabled()) log.debug("Processing local spaces.");

        for (IpcSharedMemoryClientEndpoint e : endpoints) {
          if (log.isDebugEnabled()) log.debug("Processing endpoint: " + e);

          if (!e.checkOtherPartyAlive()) {
            endpoints.remove(e);

            if (log.isDebugEnabled()) log.debug("Removed endpoint: " + e);
          }
        }

        if (isCancelled()) {
          if (lastRunNeeded) {
            lastRunNeeded = false;

            // Clear interrupted status.
            Thread.interrupted();
          } else {
            Thread.currentThread().interrupt();

            break;
          }
        }
      }
    }
  /**
   * Checks if address can be reached using one argument InetAddress.isReachable() version or ping
   * command if failed.
   *
   * @param addr Address to check.
   * @param reachTimeout Timeout for the check.
   * @return {@code True} if address is reachable.
   */
  public static boolean reachableByPing(InetAddress addr, int reachTimeout) {
    try {
      if (addr.isReachable(reachTimeout)) return true;

      String cmd = String.format("ping -%s 1 %s", U.isWindows() ? "n" : "c", addr.getHostAddress());

      Process myProc = Runtime.getRuntime().exec(cmd);

      myProc.waitFor();

      return myProc.exitValue() == 0;
    } catch (IOException ignore) {
      return false;
    } catch (InterruptedException ignored) {
      Thread.currentThread().interrupt();

      return false;
    }
  }
 /**
  * Marks the beginning of an I/O operation that might block indefinitely.
  *
  * <p>This method should be invoked in tandem with the {@link #end end} method, using a
  * <tt>try</tt>&nbsp;...&nbsp;<tt>finally</tt> block as shown <a href="#be">above</a>, in order to
  * implement asynchronous closing and interruption for this channel.
  */
 protected final void begin() {
   if (interruptor == null) {
     interruptor =
         new Interruptible() {
           public void interrupt(Thread target) {
             synchronized (closeLock) {
               if (!open) return;
               open = false;
               interrupted = target;
               try {
                 AbstractInterruptibleChannel.this.implCloseChannel();
               } catch (IOException x) {
               }
             }
           }
         };
   }
   blockedOn(interruptor);
   Thread me = Thread.currentThread();
   if (me.isInterrupted()) interruptor.interrupt(me);
 }
  /** {@inheritDoc} */
  @Override
  public void close() {
    closed = true;

    U.closeQuiet(srvSock);

    if (gcWorker != null) {
      U.cancel(gcWorker);

      // This method may be called from already interrupted thread.
      // Need to ensure cleaning on close.
      boolean interrupted = Thread.interrupted();

      try {
        U.join(gcWorker);
      } catch (IgniteInterruptedCheckedException e) {
        U.warn(log, "Interrupted when stopping GC worker.", e);
      } finally {
        if (interrupted) Thread.currentThread().interrupt();
      }
    }
  }
 // -- sun.misc.SharedSecrets --
 static void blockedOn(Interruptible intr) { // package-private
   sun.misc.SharedSecrets.getJavaLangAccess().blockedOn(Thread.currentThread(), intr);
 }
  /** {@inheritDoc} */
  @SuppressWarnings("ErrorNotRethrown")
  @Override
  public IpcEndpoint accept() throws IgniteCheckedException {
    while (!Thread.currentThread().isInterrupted()) {
      Socket sock = null;

      boolean accepted = false;

      try {
        sock = srvSock.accept();

        accepted = true;

        InputStream inputStream = sock.getInputStream();
        ObjectInputStream in = new ObjectInputStream(inputStream);

        ObjectOutputStream out = new ObjectOutputStream(sock.getOutputStream());

        IpcSharedMemorySpace inSpace = null;

        IpcSharedMemorySpace outSpace = null;

        boolean err = true;

        try {
          IpcSharedMemoryInitRequest req = (IpcSharedMemoryInitRequest) in.readObject();

          if (log.isDebugEnabled()) log.debug("Processing request: " + req);

          IgnitePair<String> p = inOutToken(req.pid(), size);

          String file1 = p.get1();
          String file2 = p.get2();

          assert file1 != null;
          assert file2 != null;

          // Create tokens.
          new File(file1).createNewFile();
          new File(file2).createNewFile();

          if (log.isDebugEnabled()) log.debug("Created token files: " + p);

          inSpace = new IpcSharedMemorySpace(file1, req.pid(), pid, size, true, log);

          outSpace = new IpcSharedMemorySpace(file2, pid, req.pid(), size, false, log);

          IpcSharedMemoryClientEndpoint ret =
              new IpcSharedMemoryClientEndpoint(inSpace, outSpace, log);

          out.writeObject(
              new IpcSharedMemoryInitResponse(
                  file2, outSpace.sharedMemoryId(), file1, inSpace.sharedMemoryId(), pid, size));

          err = !in.readBoolean();

          endpoints.add(ret);

          return ret;
        } catch (UnsatisfiedLinkError e) {
          throw IpcSharedMemoryUtils.linkError(e);
        } catch (IOException e) {
          if (log.isDebugEnabled())
            log.debug(
                "Failed to process incoming connection "
                    + "(was connection closed by another party):"
                    + e.getMessage());
        } catch (ClassNotFoundException e) {
          U.error(log, "Failed to process incoming connection.", e);
        } catch (ClassCastException e) {
          String msg =
              "Failed to process incoming connection (most probably, shared memory "
                  + "rest endpoint has been configured by mistake).";

          LT.warn(log, null, msg);

          sendErrorResponse(out, e);
        } catch (IpcOutOfSystemResourcesException e) {
          if (!omitOutOfResourcesWarn) LT.warn(log, null, OUT_OF_RESOURCES_MSG);

          sendErrorResponse(out, e);
        } catch (IgniteCheckedException e) {
          LT.error(log, e, "Failed to process incoming shared memory connection.");

          sendErrorResponse(out, e);
        } finally {
          // Exception has been thrown, need to free system resources.
          if (err) {
            if (inSpace != null) inSpace.forceClose();

            // Safety.
            if (outSpace != null) outSpace.forceClose();
          }
        }
      } catch (IOException e) {
        if (!Thread.currentThread().isInterrupted() && !accepted)
          throw new IgniteCheckedException("Failed to accept incoming connection.", e);

        if (!closed)
          LT.error(
              log, null, "Failed to process incoming shared memory connection: " + e.getMessage());
      } finally {
        U.closeQuiet(sock);
      }
    } // while

    throw new IgniteInterruptedCheckedException("Socket accept was interrupted.");
  }