/** * Returns the next available thread id. Subclasses may wish to * override this, for example if they implement a timeout */ Integer getProcessor() { try { return idleProcessors.take(); } catch (InterruptedException e) { throw new RuntimeInterruptedException(e); } }
public static void checkForInterrupt() { if (Thread.interrupted()) { throw new RuntimeInterruptedException(); } }
@Override protected Integer getProcessor() { try { return (timeout <= 0) ? idleProcessors.take() : idleProcessors.poll(timeout, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { throw new RuntimeInterruptedException(e); } }
private static void robustCreateFile(File candidate) throws IOException { int tries = 0; while ( ! candidate.exists()) { if (tries > 30) { throw new IOException("Could not create file: " + candidate); } if (candidate.createNewFile()) { break; } tries++; try { Thread.sleep(1000); } catch (InterruptedException e) { log(e); throw new RuntimeInterruptedException(e); } } }
@Override public Collection<SequencePattern<T>> apply(List<? extends T> elements) { // Use LinkedHashSet to preserve original ordering of patterns. Set<SequencePattern<T>> triggeredPatterns = new LinkedHashSet<>(); for (T node:elements) { if (Thread.interrupted()) { // Allow interrupting throw new RuntimeInterruptedException(); } Collection<SequencePattern<T>> triggered = trigger.apply(node); triggeredPatterns.addAll(triggered); } return triggeredPatterns; } }
/** Fills in the iScore array of each category over each span * of length 2 or more. */ void doInsideScores() { for (int diff = 2; diff <= length; diff++) { if (Thread.interrupted()) { throw new RuntimeInterruptedException(); } // usually stop one short because boundary symbol only combines // with whole sentence span. So for 3 word sentence + boundary = 4, // length == 4, and do [0,2], [1,3]; [0,3]; [0,4] for (int start = 0; start < ((diff == length) ? 1: length - diff); start++) { doInsideChartCell(diff, start); } // for start } // for diff (i.e., span) } // end doInsideScores()
@Override public int addToIndex(E o) { Integer index = indexes.get(o); if (index == null) { if ( ! locked) { try { semaphore.acquire(); index = indexes.get(o); if (index == null) { index = objects.size(); objects.add(o); indexes.put(o, index); } semaphore.release(); } catch (InterruptedException e) { throw new RuntimeInterruptedException(e); } } else { return -1; } } return index; }
public void close() throws IOException { process.getOutputStream().close(); try { outGobbler.join(); errGobbler.join(); outGobbler.getOutputStream().close(); process.waitFor(); } catch (InterruptedException ex) { throw new RuntimeInterruptedException(ex); } //log.info("getBZip2PipedOutputStream: Closed. "); } }
throw new RuntimeInterruptedException(e);
public void annotate(final Annotation annotation, final Consumer<Annotation> callback){ if (PropertiesUtils.getInt(properties, "threads", 1) == 1) { annotate(annotation); callback.accept(annotation); } else { try { availableProcessors.acquire(); } catch (InterruptedException e) { throw new RuntimeInterruptedException(e); } new Thread(() -> { try { annotate(annotation); } catch (Throwable t) { annotation.set(CoreAnnotations.ExceptionAnnotation.class, t); } callback.accept(annotation); availableProcessors.release(); }).start(); } }
exec.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS); } catch (InterruptedException e) { throw new RuntimeInterruptedException(e);
public void run() { Runtime runtime = Runtime.getRuntime(); timer.start(); while (true) { peak = Math.max(peak, runtime.totalMemory() - runtime.freeMemory()); if (timer.report() > logFrequency) { log(); timer.restart(); } try { Thread.sleep(pollFrequency); } catch (InterruptedException e) { log(); throw new RuntimeInterruptedException(e); } } }
private void runTagInference() { this.initializeScorer(); if (Thread.interrupted()) { // Allow interrupting throw new RuntimeInterruptedException(); } BestSequenceFinder ti = new ExactBestSequenceFinder(); //new BeamBestSequenceFinder(50); //new KBestSequenceFinder() int[] bestTags = ti.bestSequence(this); finalTags = new String[bestTags.length]; for (int j = 0; j < size; j++) { finalTags[j] = maxentTagger.tags.getTag(bestTags[j + leftWindow()]); } if (Thread.interrupted()) { // Allow interrupting throw new RuntimeInterruptedException(); } cleanUpScorer(); }
/** * Finds and returns the key in the Counter with the largest count. Returning * null if count is empty. * * @param c The Counter * @param tieBreaker the tie breaker for when elements have the same value. * @param defaultIfEmpty The value to return if the counter is empty. * @return The key in the Counter with the largest count. */ public static <E> E argmax(Counter<E> c, Comparator<E> tieBreaker, E defaultIfEmpty) { if (Thread.interrupted()) { // A good place to check for interrupts -- called from many annotators throw new RuntimeInterruptedException(); } if (c.size() == 0) { return defaultIfEmpty; } double max = Double.NEGATIVE_INFINITY; E argmax = null; for (E key : c.keySet()) { double count = c.getCount(key); if (argmax == null || count > max || (count == max && tieBreaker.compare(key, argmax) < 0)) { max = count; argmax = key; } } return argmax; }
@Override public boolean hasNext() { // Still have elements in this block if (elements.hasNext()) return true; // Still have files to traverse elements = null; while (index < files.length && elements == null) { try { elements = readBlock(files[index]).iterator(); } catch (OutOfMemoryError e) { warn("FileBackedCache", "Caught out of memory error (clearing cache): " + e.getMessage()); FileBackedCache.this.clear(); //noinspection EmptyCatchBlock try { Thread.sleep(1000); } catch (InterruptedException e2) { throw new RuntimeInterruptedException(e2); } elements = readBlock(files[index]).iterator(); } catch (RuntimeException e) { err(e); } index += 1; } // No more elements return elements != null && hasNext(); } @Override
/** * Run the pipeline on an input annotation. * The annotation is modified in place. * * @param annotation The input annotation, usually a raw document */ @Override public void annotate(Annotation annotation) { Iterator<MutableLong> it = accumulatedTime.iterator(); Timing t = new Timing(); for (Annotator annotator : annotators) { if (Thread.interrupted()) { // Allow interrupting throw new RuntimeInterruptedException(); } if (TIME) { t.start(); } annotator.annotate(annotation); if (TIME) { long elapsed = t.stop(); MutableLong m = it.next(); m.incValue(elapsed); } } }
/** * Given a sequence, applies our patterns over the sequence and returns * all non overlapping matches. When multiple patterns overlaps, * matched patterns are selected by order specified by the comparator * @param elements input sequence to match against * @param cmp comparator indicating order that overlapped sequences should be selected. * @return list of match results that are non-overlapping */ public List<SequenceMatchResult<T>> findNonOverlapping(List<? extends T> elements, Comparator<? super SequenceMatchResult> cmp) { Collection<SequencePattern<T>> triggered = getTriggeredPatterns(elements); List<SequenceMatchResult<T>> all = new ArrayList<>(); int i = 0; for (SequencePattern<T> p:triggered) { if (Thread.interrupted()) { // Allow interrupting throw new RuntimeInterruptedException(); } SequenceMatcher<T> m = p.getMatcher(elements); m.setMatchWithResult(matchWithResult); m.setOrder(i); while (m.find()) { all.add(m.toBasicSequenceMatchResult()); } i++; } List<SequenceMatchResult<T>> res = IntervalTree.getNonOverlapping( all, SequenceMatchResult.TO_INTERVAL, cmp); res.sort(SequenceMatchResult.OFFSET_COMPARATOR); return res; }
/** * Given a sequence, applies our patterns over the sequence and returns * all matches, depending on the findType. When multiple patterns overlaps, * matched patterns are selected by order specified by the comparator * @param elements input sequence to match against * @param findType whether FindType.FIND_ALL or FindType.FIND_NONOVERLAPPING * @return list of match results */ public List<SequenceMatchResult<T>> find(List<? extends T> elements, SequenceMatcher.FindType findType) { Collection<SequencePattern<T>> triggered = getTriggeredPatterns(elements); List<SequenceMatchResult<T>> all = new ArrayList<>(); int i = 0; for (SequencePattern<T> p:triggered) { if (Thread.interrupted()) { // Allow interrupting throw new RuntimeInterruptedException(); } SequenceMatcher<T> m = p.getMatcher(elements); m.setMatchWithResult(matchWithResult); m.setFindType(findType); m.setOrder(i); while (m.find()) { all.add(m.toBasicSequenceMatchResult()); } i++; } List<SequenceMatchResult<T>> res = IntervalTree.getNonOverlapping( all, SequenceMatchResult.TO_INTERVAL, SequenceMatchResult.DEFAULT_COMPARATOR); res.sort(SequenceMatchResult.OFFSET_COMPARATOR); return res; }
/** * Parse a Sentence. It is assumed that when this is called, the pparser * has already been called to parse the sentence. * * @param words The list of words to parse. * @return true iff it could be parsed */ public boolean parse(List<? extends HasWord> words) { nGoodTrees.clear(); int numParsesToConsider = numToFind * op.testOptions.fastFactoredCandidateMultiplier + op.testOptions.fastFactoredCandidateAddend; if (pparser.hasParse()) { List<ScoredObject<Tree>> pcfgBest = pparser.getKBestParses(numParsesToConsider); Beam<ScoredObject<Tree>> goodParses = new Beam<>(numToFind); for (ScoredObject<Tree> candidate : pcfgBest) { if (Thread.interrupted()) { throw new RuntimeInterruptedException(); } double depScore = depScoreTree(candidate.object()); ScoredObject<Tree> x = new ScoredObject<>(candidate.object(), candidate.score() + depScore); goodParses.add(x); } nGoodTrees = goodParses.asSortedList(); } return ! nGoodTrees.isEmpty(); }
/** * Determine the dependency parse of the given sentence. * <p> * This "inner" method returns a structure unique to this package; use {@link #predict(edu.stanford.nlp.util.CoreMap)} * for general parsing purposes. */ private DependencyTree predictInner(CoreMap sentence) { int numTrans = system.numTransitions(); Configuration c = system.initialConfiguration(sentence); while (!system.isTerminal(c)) { if (Thread.interrupted()) { // Allow interrupting throw new RuntimeInterruptedException(); } double[] scores = classifier.computeScores(getFeatureArray(c)); double optScore = Double.NEGATIVE_INFINITY; String optTrans = null; for (int j = 0; j < numTrans; ++j) { if (scores[j] > optScore) { String tr = system.transitions.get(j); if (system.canApply(c, tr)) { optScore = scores[j]; optTrans = tr; } } } system.apply(c, optTrans); } return c.tree; }