@Override
  protected Void doInBackground() throws Exception {
    // protein identification id
    Collection<Comparable> protIdentIds = controller.getIdentificationIds();

    // protein identification id and accession buffer
    Map<Comparable, String> accBuffer = new LinkedHashMap<Comparable, String>();

    // protein map
    Map<String, Protein> proteins = new HashMap<String, Protein>();

    try {
      // iterate over each protein
      for (Comparable protIdentId : protIdentIds) {
        // get mapped protein accession
        String protAcc = controller.getProteinAccession(protIdentId);
        String protAccVersion = controller.getProteinAccessionVersion(protIdentId);
        String database = controller.getSearchDatabase(protIdentId);
        AccessionResolver resolver = new AccessionResolver(protAcc, protAccVersion, database, true);
        String mappedProtAcc = resolver.isValidAccession() ? resolver.getAccession() : null;

        if (mappedProtAcc != null) {
          // get existing protein details
          Protein protDetails =
              PrideInspectorCacheManager.getInstance().getProteinDetails(mappedProtAcc);
          if (protDetails != null) {
            proteins.put(mappedProtAcc, protDetails);
          }

          accBuffer.put(protIdentId, mappedProtAcc);
          if (accBuffer.size() == MAX_BATCH_DOWNLOAD_SIZE) {
            // fetch and publish protein details
            fetchAndPublish(accBuffer, proteins);

            // clear accession buffer
            accBuffer.clear();

            // clear protein map
            proteins = new HashMap<String, Protein>();
          }
        }
      }

      // this is important for cancelling
      if (Thread.interrupted()) {
        throw new InterruptedException();
      }

      if (!accBuffer.isEmpty() || !proteins.isEmpty()) {
        fetchAndPublish(accBuffer, proteins);
      }
    } catch (InterruptedException e) {
      logger.warn("Protein name download has been cancelled");
    }

    return null;
  }
 public void lock() {
   Thread caller = Thread.currentThread();
   synchronized (this) {
     if (owner_ == null) {
       owner_ = caller;
       holds_ = 1;
       return;
     } else if (caller == owner_) {
       incHolds();
       return;
     } else {
       boolean wasInterrupted = Thread.interrupted();
       try {
         while (true) {
           try {
             wait();
           } catch (InterruptedException e) {
             wasInterrupted = true;
             // no need to notify; if we were signalled, we
             // will act as signalled, ignoring the
             // interruption
           }
           if (owner_ == null) {
             owner_ = caller;
             holds_ = 1;
             return;
           }
         }
       } finally {
         if (wasInterrupted) Thread.currentThread().interrupt();
       }
     }
   }
 }
 public void lockInterruptibly() throws InterruptedException {
   if (Thread.interrupted()) throw new InterruptedException();
   Thread caller = Thread.currentThread();
   synchronized (this) {
     if (owner_ == null) {
       owner_ = caller;
       holds_ = 1;
       return;
     } else if (caller == owner_) {
       incHolds();
       return;
     } else {
       try {
         do {
           wait();
         } while (owner_ != null);
         owner_ = caller;
         holds_ = 1;
         return;
       } catch (InterruptedException ex) {
         if (owner_ == null) notify();
         throw ex;
       }
     }
   }
 }
Ejemplo n.º 4
0
    protected void await(boolean throwInterrupt) throws InterruptedException {
      if (!signaled.get()) {
        lock.acquired = false;
        sendAwaitConditionRequest(lock.name, lock.owner);
        boolean interrupted = false;
        while (!signaled.get()) {
          parker.set(Thread.currentThread());
          LockSupport.park(this);

          if (Thread.interrupted()) {
            // If we were interrupted and haven't received a response yet then we try to
            // clean up the lock request and throw the exception
            if (!signaled.get()) {
              sendDeleteAwaitConditionRequest(lock.name, lock.owner);
              throw new InterruptedException();
            }
            // In the case that we were signaled and interrupted
            // we want to return the signal but still interrupt
            // our thread
            interrupted = true;
          }
        }
        if (interrupted) Thread.currentThread().interrupt();
      }

      // We set as if this signal was no released.  This way if the
      // condition is reused again, but the client condition isn't lost
      // we won't think we were signaled immediately
      signaled.set(false);
    }
    @Override
    public void run() {
      try {
        while (!Thread.interrupted()) {
          int curUpdateIntervalMS = updaterIntervalNoMasterMS;

          try {
            updateAll();

            updateInetAddresses();

            ReplicaSet replicaSet =
                new ReplicaSet(createNodeList(), _random, slaveAcceptableLatencyMS);
            _replicaSetHolder.set(replicaSet);

            if (replicaSet.hasMaster()) {
              _mongo.getConnector().setMaster(replicaSet.getMaster());
              curUpdateIntervalMS = updaterIntervalMS;
            }
          } catch (Exception e) {
            _logger.get().log(Level.WARNING, "couldn't do update pass", e);
          }

          Thread.sleep(curUpdateIntervalMS);
        }
      } catch (InterruptedException e) {
        // Allow thread to exit
      }

      _replicaSetHolder.close();
      closeAllNodes();
    }
  private boolean waitForAvailableConnection(long expireTime) {
    _availableWaitCount.incrementAndGet();

    try {
      synchronized (_availableLock) {
        // return false only if the timeout occurs before the wait
        boolean isAfterWait = false;

        while (!isIdleAvailable() && !isCreateAvailable()) {
          try {
            long now = CurrentTime.getCurrentTimeActual();

            long delta = expireTime - now;

            if (delta <= 0) return isAfterWait;

            Thread.interrupted();
            _availableLock.wait(delta);

            isAfterWait = true;
          } catch (InterruptedException e) {
            log.log(Level.FINER, e.toString(), e);
          }
        }

        return true;
      }
    } finally {
      _availableWaitCount.decrementAndGet();
    }
  }
Ejemplo n.º 7
0
 /**
  * Adds the specified element to this queue, waiting if necessary for another thread to receive
  * it.
  *
  * @throws InterruptedException {@inheritDoc}
  * @throws NullPointerException {@inheritDoc}
  */
 public void put(E o) throws InterruptedException {
   if (o == null) throw new NullPointerException();
   if (transferer.transfer(o, false, 0) == null) {
     Thread.interrupted();
     throw new InterruptedException();
   }
 }
Ejemplo n.º 8
0
 public void run() {
   try {
     while (!Thread.interrupted()) q.take().run(); // Run task with the current thread
   } catch (InterruptedException e) {
     // Acceptable way to exit
   }
   print("Finished DelayedTaskConsumer");
 }
Ejemplo n.º 9
0
 synchronized void waitingCall() {
   try {
     while (!Thread.interrupted()) {
       wait();
       System.out.print(Thread.currentThread() + " ");
     }
   } catch (InterruptedException e) {
     // OK to exit this way
   }
 }
Ejemplo n.º 10
0
 private synchronized void waitForFinalize() {
   while (_real == null) {
     try {
       wait();
     } catch (InterruptedException _ie) {
       // We should really let waitForFinalize throw InterruptedException
       Thread.interrupted();
     }
   }
 }
Ejemplo n.º 11
0
 public void run() {
   try {
     while (!Thread.interrupted()) {
       for (int i = 0; i < ExchangerDemo.size; i++) holder.add(generator.next());
       // Exchange full for empty:
       holder = exchanger.exchange(holder);
     }
   } catch (InterruptedException e) {
     // OK to terminate this way.
   }
 }
 public void run() {
   try {
     while (!Thread.interrupted()) {
       TimeUnit.MILLISECONDS.sleep(rand.nextInt(300));
       customers.put(new Customer(rand.nextInt(1000)));
     }
   } catch (InterruptedException e) {
     System.out.println("CustomerGenerator interrupted");
   }
   System.out.println("CustomerGenerator terminating");
 }
Ejemplo n.º 13
0
  /**
   * Waits for all workers to finish.
   *
   * @param cancel Flag to indicate whether workers should be cancelled before waiting for them to
   *     finish.
   */
  public void join(boolean cancel) {
    if (cancel) U.cancel(workers);

    // Record current interrupted status of calling thread.
    boolean interrupted = Thread.interrupted();

    try {
      U.join(workers, log);
    } finally {
      // Reset interrupted flag on calling thread.
      if (interrupted) Thread.currentThread().interrupt();
    }
  }
 public void run() {
   try {
     while (!Thread.interrupted()) {
       // Blocks until a course is ready
       Plate plate = filledOrders.take();
       print(this + "received " + plate + " delivering to " + plate.getOrder().getCustomer());
       plate.getOrder().getCustomer().deliver(plate);
     }
   } catch (InterruptedException e) {
     print(this + " interrupted");
   }
   print(this + " off duty");
 }
 public void run() {
   try {
     while (!Thread.interrupted()) {
       // A new customer arrives; assign a WaitPerson:
       WaitPerson wp = waitPersons.get(rand.nextInt(waitPersons.size()));
       Customer c = new Customer(wp);
       exec.execute(c);
       TimeUnit.MILLISECONDS.sleep(100);
     }
   } catch (InterruptedException e) {
     print("Restaurant interrupted");
   }
   print("Restaurant closing");
 }
Ejemplo n.º 16
0
 public void run() {
   try {
     while (!Thread.interrupted()) {
       holder = exchanger.exchange(holder);
       for (T x : holder) {
         value = x; // Fetch out value
         holder.remove(x); // OK for CopyOnWriteArrayList
       }
     }
   } catch (InterruptedException e) {
     // OK to terminate this way.
   }
   System.out.println("Final value: " + value);
 }
Ejemplo n.º 17
0
 public void run() {
   try {
     while (!Thread.interrupted()) {
       // Blocks until next piece of toast is available:
       Toast t = dryQueue.take();
       t.butter();
       print(t);
       butteredQueue.put(t);
     }
   } catch (InterruptedException e) {
     print("Butterer interrupted");
   }
   print("Butterer off");
 }
 public void run() {
   try {
     while (!Thread.interrupted()) {
       TimeUnit.MILLISECONDS.sleep(adjustmentPeriod);
       adjustTellerNumber();
       System.out.print(customers + " { ");
       for (Teller teller : workingTellers) System.out.print(teller.shortString() + " ");
       System.out.println("}");
     }
   } catch (InterruptedException e) {
     System.out.println(this + "interrupted");
   }
   System.out.println(this + "terminating");
 }
 private void saveData(final BuildFSState fsState, File dataStorageRoot) {
   final boolean wasInterrupted = Thread.interrupted();
   try {
     saveFsState(dataStorageRoot, fsState);
     final ProjectDescriptor pd = myProjectDescriptor;
     if (pd != null) {
       pd.release();
     }
   } finally {
     if (wasInterrupted) {
       Thread.currentThread().interrupt();
     }
   }
 }
    /** {@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;
          }
        }
      }
    }
 /** @see java.lang.Runnable#run() */
 public void run() {
   final Thread thread = Thread.currentThread();
   while (!Thread.interrupted()) {
     m_set.add(m_touchable);
     m_list.add(m_touchable);
     try {
       synchronized (thread) {
         thread.wait();
       }
     } catch (InterruptedException e) {
       // propagate interrupt
       thread.interrupt();
     }
   }
 }
 public void run() {
   try {
     while (!Thread.interrupted()) {
       Customer customer = customers.take();
       TimeUnit.MILLISECONDS.sleep(customer.getServiceTime());
       synchronized (this) {
         customersServed++;
         while (!servingCustomerLine) wait();
       }
     }
   } catch (InterruptedException e) {
     System.out.println(this + "interrupted");
   }
   System.out.println(this + "terminating");
 }
Ejemplo n.º 23
0
 public void sendEvent(Event event) {
   // The implementation does not need to take any locks.
   try {
     if (Thread.interrupted()) {
       // Interrupt should not happen. Mondrian uses cancel without
       // setting interrupt. But if interrupts are happening, it's
       // best to know now, rather than failing next time we make a
       // blocking system call.
       throw new AssertionError();
     }
     ACTOR.eventQueue.put(Pair.<Handler, Message>of(handler, event));
   } catch (InterruptedException e) {
     throw Util.newError(e, "Exception while sending event " + event);
   }
 }
Ejemplo n.º 24
0
 public void run() {
   try {
     while (!Thread.interrupted()) {
       TimeUnit.MILLISECONDS.sleep(100 + rand.nextInt(500));
       // Make toast
       Toast t = new Toast(count++);
       print(t);
       // Insert into queue
       toastQueue.put(t);
     }
   } catch (InterruptedException e) {
     print("Toaster interrupted");
   }
   print("Toaster off");
 }
Ejemplo n.º 25
0
  protected Exception postJsonToPipelineWithRetry(
      String endpoint, List docs, ArrayList<String> mutable, Exception lastExc, int requestId)
      throws Exception {
    Exception retryAfterException = null;

    try {
      postJsonToPipeline(endpoint, docs, requestId);
      if (lastExc != null)
        log.info(
            "Re-try request "
                + requestId
                + " to "
                + endpoint
                + " succeeded after seeing a "
                + lastExc.getMessage());
    } catch (Exception exc) {
      log.warn("Failed to send request " + requestId + " to '" + endpoint + "' due to: " + exc);
      if (mutable.size() > 1) {
        // try another endpoint but update the cloned list to avoid re-hitting the one having an
        // error
        if (log.isDebugEnabled())
          log.debug("Will re-try failed request " + requestId + " on next endpoint in the list");

        mutable.remove(endpoint);
        retryAfterException = exc;
      } else {
        // no other endpoints to try ... brief wait and then retry
        log.warn(
            "No more endpoints available to try ... will retry to send request "
                + requestId
                + " to "
                + endpoint
                + " after waiting 1 sec");
        try {
          Thread.sleep(1000);
        } catch (InterruptedException ignore) {
          Thread.interrupted();
        }
        // note we want the exception to propagate from here up the stack since we re-tried and it
        // didn't work
        postJsonToPipeline(endpoint, docs, requestId);
        log.info("Re-try request " + requestId + " to " + endpoint + " succeeded");
        retryAfterException = null; // return success condition
      }
    }

    return retryAfterException;
  }
 public void run() {
   try {
     while (!Thread.interrupted()) {
       // Blocks until an order appears:
       Order order = restaurant.orders.take();
       Food requestedItem = order.item();
       // Time to prepare order:
       TimeUnit.MILLISECONDS.sleep(rand.nextInt(500));
       Plate plate = new Plate(order, requestedItem);
       order.getWaitPerson().filledOrders.put(plate);
     }
   } catch (InterruptedException e) {
     print(this + " interrupted");
   }
   print(this + " off duty");
 }
 public void lockInterruptibly() throws InterruptedException {
   if (Thread.interrupted()) throw new InterruptedException();
   Thread caller = Thread.currentThread();
   synchronized (this) {
     if (owner_ == null) {
       owner_ = caller;
       holds_ = 1;
       return;
     } else if (caller == owner_) {
       incHolds();
       return;
     }
   }
   WaitQueue.WaitNode n = new WaitQueue.WaitNode();
   n.doWait(this);
 }
 public boolean tryLock(long nanos) throws InterruptedException {
   if (Thread.interrupted()) throw new InterruptedException();
   Thread caller = Thread.currentThread();
   synchronized (this) {
     if (owner_ == null) {
       owner_ = caller;
       holds_ = 1;
       return true;
     } else if (caller == owner_) {
       incHolds();
       return true;
     }
   }
   WaitQueue.WaitNode n = new WaitQueue.WaitNode();
   return n.doTimedWait(this, nanos);
 }
Ejemplo n.º 29
0
 public void run() {
   try {
     while (!Thread.interrupted()) {
       // Blocks until next piece of toast is available:
       Toast t = finishedQueue.take();
       // Verify that the toast is coming in order,
       // and that all pieces are getting jammed:
       if (t.getId() != counter++ || t.getStatus() != Toast.Status.JAMMED) {
         print(">>>> Error: " + t);
         System.exit(1);
       } else print("Chomp! " + t);
     }
   } catch (InterruptedException e) {
     print("Eater interrupted");
   }
   print("Eater off");
 }
Ejemplo n.º 30
0
    protected long await(long nanoSeconds) throws InterruptedException {
      long target_nano = System.nanoTime() + nanoSeconds;

      if (!signaled.get()) {
        // We release the lock at the same time as waiting on the
        // condition
        lock.acquired = false;
        sendAwaitConditionRequest(lock.name, lock.owner);

        boolean interrupted = false;
        while (!signaled.get()) {
          long wait_nano = target_nano - System.nanoTime();
          // If we waited max time break out
          if (wait_nano > 0) {
            parker.set(Thread.currentThread());
            LockSupport.parkNanos(this, wait_nano);

            if (Thread.interrupted()) {
              // If we were interrupted and haven't received a response yet then we try to
              // clean up the lock request and throw the exception
              if (!signaled.get()) {
                sendDeleteAwaitConditionRequest(lock.name, lock.owner);
                throw new InterruptedException();
              }
              // In the case that we were signaled and interrupted
              // we want to return the signal but still interrupt
              // our thread
              interrupted = true;
            }
          } else {
            break;
          }
        }
        if (interrupted) Thread.currentThread().interrupt();
      }

      // We set as if this signal was no released.  This way if the
      // condition is reused again, but the client condition isn't lost
      // we won't think we were signaled immediately
      // If we weren't signaled then delete our request
      if (!signaled.getAndSet(false)) {
        sendDeleteAwaitConditionRequest(lock.name, lock.owner);
      }
      return target_nano - System.nanoTime();
    }