List of usage examples for org.apache.commons.lang3.mutable MutableBoolean MutableBoolean
public MutableBoolean(final Boolean value)
From source file:org.apache.pulsar.broker.loadbalance.impl.OverloadShedder.java
/** * Attempt to shed some bundles off every broker which is overloaded. * * @param loadData/*from ww w. j av a 2s.com*/ * The load data to used to make the unloading decision. * @param conf * The service configuration. * @return A map from bundles to unload to the brokers on which they are loaded. */ public Multimap<String, String> findBundlesForUnloading(final LoadData loadData, final ServiceConfiguration conf) { selectedBundlesCache.clear(); final double overloadThreshold = conf.getLoadBalancerBrokerOverloadedThresholdPercentage() / 100.0; final Map<String, Long> recentlyUnloadedBundles = loadData.getRecentlyUnloadedBundles(); // Check every broker and select loadData.getBrokerData().forEach((broker, brokerData) -> { final LocalBrokerData localData = brokerData.getLocalData(); final double currentUsage = localData.getMaxResourceUsage(); if (currentUsage < overloadThreshold) { if (log.isDebugEnabled()) { log.debug("[{}] Broker is not overloaded, ignoring at this point", broker); } return; } // We want to offload enough traffic such that this broker will go below the overload threshold // Also, add a small margin so that this broker won't be very close to the threshold edge. double percentOfTrafficToOffload = currentUsage - overloadThreshold + ADDITIONAL_THRESHOLD_PERCENT_MARGIN; double brokerCurrentThroughput = localData.getMsgThroughputIn() + localData.getMsgThroughputOut(); double minimumThroughputToOffload = brokerCurrentThroughput * percentOfTrafficToOffload; log.info( "Attempting to shed load on {}, which has max resource usage above threshold {}% > {}% -- Offloading at least {} MByte/s of traffic", broker, currentUsage, overloadThreshold, minimumThroughputToOffload / 1024 / 1024); MutableDouble trafficMarkedToOffload = new MutableDouble(0); MutableBoolean atLeastOneBundleSelected = new MutableBoolean(false); if (localData.getBundles().size() > 1) { // Sort bundles by throughput, then pick the biggest N which combined make up for at least the minimum throughput to offload loadData.getBundleData().entrySet().stream().map((e) -> { // Map to throughput value // Consider short-term byte rate to address system resource burden String bundle = e.getKey(); BundleData bundleData = e.getValue(); TimeAverageMessageData shortTermData = bundleData.getShortTermData(); double throughput = shortTermData.getMsgThroughputIn() + shortTermData.getMsgThroughputOut(); return Pair.of(bundle, throughput); }).filter(e -> { // Only consider bundles that were not already unloaded recently return !recentlyUnloadedBundles.containsKey(e.getLeft()); }).sorted((e1, e2) -> { // Sort by throughput in reverse order return Double.compare(e2.getRight(), e1.getRight()); }).forEach(e -> { if (trafficMarkedToOffload.doubleValue() < minimumThroughputToOffload || atLeastOneBundleSelected.isFalse()) { selectedBundlesCache.put(broker, e.getLeft()); trafficMarkedToOffload.add(e.getRight()); atLeastOneBundleSelected.setTrue(); } }); } else if (localData.getBundles().size() == 1) { log.warn( "HIGH USAGE WARNING : Sole namespace bundle {} is overloading broker {}. " + "No Load Shedding will be done on this broker", localData.getBundles().iterator().next(), broker); } else { log.warn("Broker {} is overloaded despite having no bundles", broker); } }); return selectedBundlesCache; }
From source file:org.jbpm.bpmn2.IntermediateEventTest.java
@Test public void testSignalBoundaryNonEffectiveEvent() throws Exception { final String signal = "signalTest"; final MutableBoolean eventAfterNodeLeftTriggered = new MutableBoolean(false); KieBase kbase = createKnowledgeBase("BPMN2-BoundaryEventWithNonEffectiveSignal.bpmn2"); StatefulKnowledgeSession ksession = createKnowledgeSession(kbase); TestWorkItemHandler handler = new TestWorkItemHandler(); ksession.getWorkItemManager().registerWorkItemHandler("Human Task", handler); ksession.addEventListener(new DefaultProcessEventListener() { @Override/*from w w w . j a v a 2 s . co m*/ public void afterNodeLeft(ProcessNodeLeftEvent event) { // BoundaryEventNodeInstance if (signal.equals(event.getNodeInstance().getNodeName())) { eventAfterNodeLeftTriggered.setTrue(); } } }); ProcessInstance processInstance = ksession.startProcess("BoundaryEventWithNonEffectiveSignal"); ksession.signalEvent(signal, signal); // outer human work ksession.getWorkItemManager().completeWorkItem(handler.getWorkItem().getId(), null); // inner human task ksession.getWorkItemManager().completeWorkItem(handler.getWorkItem().getId(), null); assertProcessInstanceFinished(processInstance, ksession); assertThat(eventAfterNodeLeftTriggered.isFalse()).isTrue(); }
From source file:org.lockss.scheduler.TestTaskRunner.java
public void testRunStepsOneTaskAndCallback() { final List finished = new ArrayList(); TaskCallback cb = new TaskCallback() { public void taskEvent(SchedulableTask task, Schedule.EventType event) { if (event == Schedule.EventType.FINISH) { finished.add(task);/*from ww w. java2s. c om*/ } } }; StepTask t1 = task(100, 200, 100, cb, new MyMockStepper(10, -10)); Schedule s = sched(ListUtil.list(t1)); fact.setResult(s); assertTrue(tr.addToSchedule(t1)); TimeBase.setSimulated(101); assertTrue(tr.findTaskToRun()); Interrupter intr = null; try { intr = interruptMeIn(TIMEOUT_SHOULDNT, true); tr.runSteps(new MutableBoolean(true), null); intr.cancel(); } catch (Exception e) { log.error("runSteps threw:", e); } finally { if (intr.did()) { fail("runSteps looped"); } } assertSame(t1, finished.get(0)); assertNull(t1.e); }
From source file:org.lockss.scheduler.TestTaskRunner.java
public void testRunStepsWithOverrunDisallowed() { StepTask t1 = task(100, 300, 100, null, new MyMockStepper(15, -10)); // t1.setOverrunAllowed(true); StepTask t2 = task(150, 250, 100, null, new MyMockStepper(10, -10)); Schedule s = sched(ListUtil.list(t1, t2)); fact.setResults(s, s);//www.j av a 2 s . co m assertTrue(tr.addToSchedule(t1)); assertTrue(tr.addToSchedule(t2)); TimeBase.setSimulated(101); Interrupter intr = null; try { intr = interruptMeIn(TIMEOUT_SHOULDNT, true); while (tr.findTaskToRun()) { tr.runSteps(new MutableBoolean(true), null); } intr.cancel(); } catch (Exception e) { log.error("runSteps threw:", e); } finally { if (intr.did()) { fail("runSteps looped"); } } assertEquals(SetUtil.set(t1, t2), SetUtil.theSet(removedTasks)); assertTrue(t1.e.toString(), t1.e instanceof SchedService.Overrun); }
From source file:org.lockss.scheduler.TestTaskRunner.java
public void testRunStepsWithOverrunAllowed() { StepTask t1 = task(100, 500, 30, null, new MyMockStepper(15, -10)); t1.setOverrunAllowed(true);/*from www. j av a 2s. c o m*/ StepTask t2 = task(150, 250, 100, null, new MyMockStepper(10, -10)); newTr(new MyMockTaskRunner(new TaskRunner.SchedulerFactory() { public Scheduler createScheduler() { return new SortScheduler(); } })); assertTrue(tr.addToSchedule(t1)); assertTrue(tr.addToSchedule(t2)); TimeBase.setSimulated(101); assertTrue(tr.findTaskToRun()); Interrupter intr = null; try { intr = interruptMeIn(TIMEOUT_SHOULDNT, true); while (tr.findTaskToRun()) { tr.runSteps(new MutableBoolean(true), null); } intr.cancel(); } catch (Exception e) { log.error("runSteps threw:", e); } finally { if (intr.did()) { fail("runSteps looped"); } } assertNull(t1.e); assertTrue(t1.hasOverrun()); }
From source file:org.lockss.scheduler.TestTaskRunner.java
public void testStepperThrows() { final List finished = new ArrayList(); TaskCallback cb = new TaskCallback() { public void taskEvent(SchedulableTask task, Schedule.EventType event) { if (event == Schedule.EventType.FINISH) { finished.add(task);// www .j a v a 2s. c o m } } }; MyMockStepper stepper = new MyMockStepper(10, -10); stepper.setWhenToThrow(5); StepTask t1 = task(100, 200, 100, cb, stepper); Schedule s = sched(ListUtil.list(t1)); fact.setResult(s); assertTrue(tr.addToSchedule(t1)); TimeBase.setSimulated(101); assertTrue(tr.findTaskToRun()); Interrupter intr = null; try { intr = interruptMeIn(TIMEOUT_SHOULDNT, true); tr.runSteps(new MutableBoolean(true), null); intr.cancel(); } catch (Exception e) { log.error("runSteps threw:", e); } finally { if (intr.did()) { fail("runSteps looped"); } } assertSame(t1, finished.get(0)); assertTrue(t1.e instanceof ExpectedRuntimeException); assertEquals(5, stepper.nSteps); }
From source file:org.lockss.servlet.BatchAuConfig.java
private void chooseSets(Verb verb) throws IOException { this.verb = verb; // Begin page Page page = newPage();//from w w w . j a v a2 s. c o m addJavaScript(page); layoutErrorBlock(page); // Prepare sets Collection titleSets = pluginMgr.getTitleSets(); if (titleSets.isEmpty()) { ServletUtil.layoutExplanationBlock(page, "No titlesets are defined."); } else { String grayAction = CurrentConfig.getParam(PARAM_GREY_TITLESET_ACTION, DEFAULT_GREY_TITLESET_ACTION); boolean doGray = "All".equalsIgnoreCase(grayAction) || (verb == VERB_ADD && "Add".equalsIgnoreCase(grayAction)); MutableBoolean isAnySelectable = new MutableBoolean(false); MutableInt buttonNumber = new MutableInt(submitButtonNumber); Composite chooseSets = ServletUtil.makeChooseSets(this, remoteApi, titleSets.iterator(), verb, KEY_TITLE_SET, doGray, isAnySelectable, "Select AUs", ACTION_SELECT_AUS, buttonNumber, 10); submitButtonNumber = buttonNumber.intValue(); if (isAnySelectable.booleanValue()) { // Display set chooser ServletUtil.layoutExplanationBlock(page, "Select one or more collections of AUs to " + verb.word + ", then click \"Select AUs\"."); ServletUtil.layoutChooseSets(srvURL(myServletDescr()), page, chooseSets, ACTION_TAG, KEY_VERB, verb); } else { // Set chooser not needed String msg = "All AUs in all predefined collections of AUs " + "already exist on this LOCKSS box."; ServletUtil.layoutExplanationBlock(page, msg); } } endPage(page); }
From source file:org.lockss.util.CXSerializer.java
/** * <p>Deserializes an object from the given file, and overwrites the * input file in XStream format if the original file was in Castor * format (when this serializer is in XSTREAM_OVERWIRTE_MODE).</p> * <p>See {@link ObjectSerializer#deserialize(File)} for a * description of this method's specification.</p> * @param inputFile {@inheritDoc}/*from www. j a va2s . c om*/ * @throws SerializationException.FileNotFound {@inheritDoc} * @throws SerializationException {@inheritDoc} * @throws InterruptedIOException {@inheritDoc} */ public Object deserialize(File inputFile) throws SerializationException, InterruptedIOException { // Open reader BufferedReader reader = null; try { reader = new BufferedReader(new FileReader(inputFile)); } catch (FileNotFoundException fnfe) { throw new SerializationException.FileNotFound(fnfe); } // Local variables MutableBoolean wasCastor = new MutableBoolean(false); Object ret = null; // Deserialize try { ret = deserialize(reader, wasCastor); } catch (SerializationException se) { // must close reader to unlock inputFile // because failDeserialize manipulates it IOUtil.safeClose(reader); throw failDeserialize(se, inputFile); } catch (InterruptedIOException iioe) { // must close reader to unlock inputFile // because failDeserialize manipulates it IOUtil.safeClose(reader); throw failDeserialize(iioe, inputFile); } finally { IOUtil.safeClose(reader); } // Overwrite if (getCompatibilityMode() == XSTREAM_OVERWRITE_MODE && wasCastor.booleanValue()) { boolean shouldThrow = CurrentConfig.getBooleanParam(PARAM_FAILED_OVERWRITE_THROWS, DEFAULT_FAILED_OVERWRITE_THROWS); try { serialize(inputFile, ret); } catch (SerializationException se) { logger.debug("Overwrite failed", se); if (shouldThrow) { throw failDeserialize(se, inputFile); } } catch (InterruptedIOException iioe) { logger.debug("Overwrite interrupted", iioe); if (shouldThrow) { throw failDeserialize(iioe, inputFile); } } catch (RuntimeException re) { logger.debug("Overwrite caused runtime exception", re); if (shouldThrow) { throw re; } } } return ret; }
From source file:org.lockss.util.CXSerializer.java
public Object deserialize(Reader reader) throws SerializationException, InterruptedIOException { return deserialize(reader, new MutableBoolean(false)); }
From source file:org.objectweb.proactive.core.remoteobject.RemoteObjectSet.java
/** * Select the best suited RemoteRemoteObject (protocol related), and send it the Request * Fallback to default (according to the PA_COMMUNICATION_PROTOCOL property) if necessary *//*from ww w .j av a 2s .c o m*/ public Reply receiveMessage(Request message) throws ProActiveException, RenegotiateSessionException, IOException { if (forcedProtocol != null) { return forcedProtocol.receiveMessage(message); } RemoteRemoteObject rro = null; // the order is cloned to allow asynchronous updates by the benchmark threads ReentrantReadWriteLock.ReadLock rl = rwlock.readLock(); rl.lock(); ArrayList<URI> cloned = (ArrayList<URI>) sortedrros.clone(); rl.unlock(); // For each protocol already selected and sorted Throwable defaultProtocolException = null; MutableBoolean anyException = new MutableBoolean(false); Reply reply = null; for (URI uri : cloned) { rro = rros.get(uri); if (LOGGER_RO.isDebugEnabled()) { LOGGER_RO.debug("[ROAdapter] Sending message " + message + " to " + uri); } try { reply = rro.receiveMessage(message); // These Exceptions happened on client side // RMI doesn't act as others protocols and Exceptions aren't // encapsulated, so they are caught here. } catch (ProtocolException pae) { defaultProtocolException = handleProtocolException(pae, uri, cloned.size() > 1, anyException); } catch (IOException io) { defaultProtocolException = handleProtocolException(io, uri, cloned.size() > 1, anyException); } catch (RenegotiateSessionException rse) { defaultProtocolException = handleProtocolException(rse, uri, cloned.size() > 1, anyException); } if (reply != null) { // The Exception is thrown on server side // So it is encapsulated to be delivered on client side Throwable t = reply.getResult().getException(); if (t != null && (t instanceof ProtocolException || t instanceof IOException || t instanceof RenegotiateSessionException)) { defaultProtocolException = handleProtocolException(t, uri, cloned.size() > 1, anyException); continue; } break; } } // if we arrive to this point either a reply has been received or all protocols sent exceptions // if there has been any exception we sort the uri list before sending back the result if (anyException.getValue()) { sortProtocolsInternal(); } // In case all protocols led to Exception, simply throw the Exception sent by the default protocol if (reply == null && defaultProtocolException != null) { if (defaultProtocolException instanceof ProtocolException) { throw (ProtocolException) defaultProtocolException; } else if (defaultProtocolException instanceof IOException) { throw (IOException) defaultProtocolException; } else if (defaultProtocolException instanceof RenegotiateSessionException) { throw (RenegotiateSessionException) defaultProtocolException; } } // otherwise, we received a reply return reply; }