Runs a check in the ThreadPool for the {@link EvaluatorManager} to wait for it to finish its
Event Handling and check its idleness source.
@param manager the {@link EvaluatorManager}
3850
void runCheckAsync(final EvaluatorManager manager) {

    final String evaluatorId = manager.getId();
    LOG.log(Level.FINEST, "Idle check for Evaluator: {0}", manager);

    this.executor.submit(new Runnable() {

      @Override
      public void run() {

        LOG.log(Level.FINEST, "Idle check for Evaluator {0} - begin", evaluatorId);

        while (!manager.isClosed()) {
          try {

            LOG.log(Level.FINEST,
                "Waiting for Evaluator {0} to close: Sleep for {1} ms",
                new Object[] {evaluatorId, waitInMillis});

            Thread.sleep(waitInMillis);

          } catch (final InterruptedException e) {
            LOG.log(Level.SEVERE, "Thread interrupted while waiting for Evaluator to finish.");
            throw new RuntimeException(e);
          }
        }

        manager.checkIdlenessSource();

        LOG.log(Level.FINEST, "Idle check for Evaluator {0} - end", evaluatorId);
      }

      @Override
      public String toString() {
        return "CheckIdle: " + evaluatorId;
      }
    });
  }
719876
private synchronized void createExecutor() {
        if (componentConfig == null) {
            // this is a completely normal occurrence and can happen if a ThreadFactory is bound prior to
            // component activation...  the proper thing to do is to do nothing and wait for activation
            return;
        }

        if (threadPoolController != null)
            threadPoolController.deactivate();

        ThreadPoolExecutor oldPool = threadPool;

        poolName = (String) componentConfig.get("name");
        String threadGroupName = poolName + " Thread Group";

        int coreThreads = Integer.parseInt(String.valueOf(componentConfig.get("coreThreads")));
        int maxThreads = Integer.parseInt(String.valueOf(componentConfig.get("maxThreads")));

        if (maxThreads <= 0) {
            maxThreads = Integer.MAX_VALUE;
        }

        if (coreThreads < 0) {
            coreThreads = 2 * CpuInfo.getAvailableProcessors();
        }

        // Make sure coreThreads is not bigger than maxThreads, subject to MINIMUM_POOL_SIZE limit
        coreThreads = Math.max(MINIMUM_POOL_SIZE, Math.min(coreThreads, maxThreads));
        // ... and then make sure maxThreads is not smaller than coreThreads ...
        maxThreads = Math.max(coreThreads, maxThreads);

        BlockingQueue<Runnable> workQueue = new BoundedBuffer<Runnable>(java.lang.Runnable.class, 1000, 1000);

        RejectedExecutionHandler rejectedExecutionHandler = new ExpandPolicy(workQueue, this);

        threadPool = new ThreadPoolExecutor(coreThreads, maxThreads, 0, TimeUnit.MILLISECONDS, workQueue, threadFactory != null ? threadFactory : new ThreadFactoryImpl(poolName, threadGroupName), rejectedExecutionHandler);

        threadPoolController = new ThreadPoolController(this, threadPool);

        if (oldPool != null) {
            softShutdown(oldPool);
        }
    }
1082443
@Override
	public synchronized void initialize(Manager manager) {
		if (this.manager != null) {
			throw new IllegalStateException("Callback was already initialized");
		}
		this.manager = manager;
		for (Callback callback : callbacks) {
			try {
				callback.initialize(manager);
			} catch (Exception e) {
				onManagerWarning("Callback initialization error", e);
			}
		}
	}
887414
@Override
    public void doMessageReceivedListeners(final Object message) {
        runManagementTask(new Runnable() {
            @Override
            public void run() {
                try {
                    List<SessionManagementListener> sessionListeners = getManagementListeners();
                    for (final SessionManagementListener listener : sessionListeners) {
                        listener.doMessageReceived(SessionManagementBeanImpl.this, message);
                    }

                    markChanged();
                } catch (Exception ex) {
                    logger.warn("Error during doMessageReceived session listener notifications:", ex);
                }
            }
        });
    }
1353245
public void setWorkplaceManager(CmsWorkplaceManager manager) {

        m_workplaceManager = manager;
        if (CmsLog.INIT.isInfoEnabled()) {
            CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_WORKPLACE_INIT_FINISHED_0));
        }
    }
845576
public void run()
    {
        try
        {
            if (!thread.compareAndSet(null, Thread.currentThread()))
            {
                return;
            }

            final IdleStrategy idleStrategy = this.idleStrategy;
            final Agent agent = this.agent;
            try
            {
                agent.onStart();
            }
            catch (final Throwable throwable)
            {
                errorHandler.onError(throwable);
                isRunning = false;
            }

            while (isRunning)
            {
                if (doDutyCycle(idleStrategy, agent))
                {
                    break;
                }
            }

            try
            {
                agent.onClose();
            }
            catch (final Throwable throwable)
            {
                errorHandler.onError(throwable);
            }
        }
        finally
        {
            isClosed = true;
        }
    }
801841
public void run() {
        SupervisorManger supervisorManager;
        try {
            Map<Object, Object> conf = Utils.readStormConfig();

            StormConfig.validate_distributed_mode(conf);

            createPid(conf);

            supervisorManager = mkSupervisor(conf, null);

            JStormUtils.redirectOutput("/dev/null");

            initShutdownHook(supervisorManager);

            while (!supervisorManager.isFinishShutdown()) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException ignored) {
                }
            }

        } catch (Throwable e) {
            if (e instanceof OutOfMemoryError) {
                LOG.error("Halting due to out of memory error...");
            }
            LOG.error("Fail to run supervisor ", e);
            System.exit(1);
        } finally {
            LOG.info("Shutdown supervisor!!!");
        }

    }
1064080
protected DestroyableManager configureManager(final DestroyableManager manager) {
        bind(DestroyableManager.class).toInstance(manager);
        // if logic will not call destroy at least it will be called before jvm shutdown
        Runtime.getRuntime().addShutdownHook(new Thread(manager));
        return manager;
    }
1235134
private void runAndWait() throws Exception {
		// Start server thread
		server.start();
		Logger logger = LoggerFactory.getLogger(SimonJolokiaDemo.class);
		logger.info("Jolokia Agent started http://localhost:8778/jolokia/");
		logger.info("Search http://localhost:8778/jolokia/search/org.javasimon:*");
		logger.info("Manager http://localhost:8778/jolokia/read/org.javasimon:type=Manager");
		logger.info("Stopwatch http://localhost:8778/jolokia/read/org.javasimon:name=A,type=Stopwatch");
		logger.info("Counter http://localhost:8778/jolokia/read/org.javasimon:name=X,type=Counter");
		BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

		String line;
		boolean stop = false;
		while (!stop && (line = reader.readLine()) != null) {
			stop = line.toLowerCase().contains("stop");
		}
	}
1284854
void onNextJVM(final AllocatedEvaluator allocatedEvaluator) {
    try {
      final Configuration contextConfiguration = ContextConfiguration.CONF
          .set(ContextConfiguration.IDENTIFIER, "HelloREEFContext")
          .build();

      final Configuration taskConfiguration = TaskConfiguration.CONF
          .set(TaskConfiguration.IDENTIFIER, "HelloREEFTask")
          .set(TaskConfiguration.TASK, HelloTask.class)
          .build();

      allocatedEvaluator.submitContextAndTask(contextConfiguration, taskConfiguration);
    } catch (final BindException ex) {
      final String message = "Unable to setup Task or Context configuration.";
      LOG.log(Level.SEVERE, message, ex);
      throw new RuntimeException(message, ex);
    }
  }
82175
public void run() {
    if (workQueue.array == null) { // only run once
      Throwable exception = null;
      try {
        onStart();
        pool.runWorker(workQueue);
      } catch (Throwable ex) {
        exception = ex;
      } finally {
        try {
          onTermination(exception);
        } catch (Throwable ex) {
          if (exception == null) {
            exception = ex;
          }
        } finally {
          pool.deregisterWorker(this, exception);
        }
      }
    }
  }
971670
public void registerWorkManager(WorkManager wm)
   {
      if (wm != null)
      {
         if (wm.getName() == null || wm.getName().trim().equals(""))
            throw new IllegalArgumentException("The name of WorkManager is invalid: " + wm);

         if (trace)
            log.tracef("Registering WorkManager: %s", wm);

         if (!workmanagers.keySet().contains(wm.getName()))
         {
            workmanagers.put(wm.getName(), wm);

            // Replay events for distributed work managers
            if (wm instanceof DistributedWorkManager)
            {
               WorkManagerEventQueue wmeq = WorkManagerEventQueue.getInstance();
               List<WorkManagerEvent> events = wmeq.getEvents(wm.getName());

               if (!events.isEmpty())
               {
                  if (trace)
                     log.tracef("%s: Events=%s", wm.getName(), events);

                  for (WorkManagerEvent event : events)
                  {
                     if (event.getType() == WorkManagerEvent.TYPE_JOIN)
                     {
                        DistributedWorkManager dwm = resolveDistributedWorkManager(event.getAddress());

                        if (dwm != null)
                        {
                           Collection<NotificationListener> copy =
                              new ArrayList<>(dwm.getNotificationListeners());
                           for (NotificationListener nl : copy)
                           {
                              nl.join(event.getAddress());
                           }
                        }
                     }
                     else if (event.getType() == WorkManagerEvent.TYPE_LEAVE)
                     {
                        DistributedWorkManager dwm = 
                           (DistributedWorkManager)activeWorkmanagers.get(event.getAddress().getWorkManagerId());

                        if (dwm != null)
                        {
                           Collection<NotificationListener> copy =
                              new ArrayList<NotificationListener>(dwm.getNotificationListeners());
                           for (NotificationListener nl : copy)
                           {
                              nl.leave(event.getAddress());
                           }
                        }

                        removeWorkManager(event.getAddress().getWorkManagerId());
                     }
                     else if (event.getType() == WorkManagerEvent.TYPE_UPDATE_SHORT_RUNNING)
                     {
                        DistributedWorkManager dwm = 
                           (DistributedWorkManager)activeWorkmanagers.get(event.getAddress().getWorkManagerId());

                        if (dwm != null)
                        {
                           Collection<NotificationListener> copy =
                              new ArrayList<NotificationListener>(dwm.getNotificationListeners());
                           for (NotificationListener nl : copy)
                           {
                              nl.updateShortRunningFree(event.getAddress(), event.getValue());
                           }
                        }
                     }
                     else if (event.getType() == WorkManagerEvent.TYPE_UPDATE_LONG_RUNNING)
                     {
                        DistributedWorkManager dwm = 
                           (DistributedWorkManager)activeWorkmanagers.get(event.getAddress().getWorkManagerId());

                        if (dwm != null)
                        {
                           Collection<NotificationListener> copy =
                              new ArrayList<NotificationListener>(dwm.getNotificationListeners());
                           for (NotificationListener nl : copy)
                           {
                              nl.updateLongRunningFree(event.getAddress(), event.getValue());
                           }
                        }
                     }
                  }
               }
            }
         }
      }
   }
509624
protected void appendEventGuardEvaluators(JvmGenericType container) {
		final GenerationContext context = getContext(container);
		if (context != null) {
			final Collection<Pair<SarlBehaviorUnit, Collection<Procedure1<? super ITreeAppendable>>>> allEvaluators
					= context.getGuardEvaluationCodes();
			if (allEvaluators == null || allEvaluators.isEmpty()) {
				return;
			}

			final JvmTypeReference voidType = this._typeReferenceBuilder.typeRef(Void.TYPE);
			final JvmTypeReference runnableType = this._typeReferenceBuilder.typeRef(Runnable.class);
			final JvmTypeReference collectionType = this._typeReferenceBuilder.typeRef(Collection.class, runnableType);
			for (final Pair<SarlBehaviorUnit, Collection<Procedure1<? super ITreeAppendable>>> evaluators : allEvaluators) {
				final SarlBehaviorUnit source = evaluators.getKey();
				// Determine the name of the operation for the behavior output
				final String behName = Utils.createNameForHiddenGuardGeneralEvaluatorMethod(source.getName().getSimpleName());

				// Create the main function
				final JvmOperation operation = this.typesFactory.createJvmOperation();

				// Annotation for the event bus

				appendGeneratedAnnotation(operation, context);
				addAnnotationSafe(operation, PerceptGuardEvaluator.class);

				// Guard evaluator unit parameters
				// - Event occurrence
				JvmFormalParameter jvmParam = this.typesFactory.createJvmFormalParameter();
				jvmParam.setName(this.grammarKeywordAccess.getOccurrenceKeyword());
				jvmParam.setParameterType(this.typeBuilder.cloneWithProxies(source.getName()));
				this.associator.associate(source, jvmParam);
				operation.getParameters().add(jvmParam);
				// - List of runnables
				jvmParam = this.typesFactory.createJvmFormalParameter();
				jvmParam.setName(RUNNABLE_COLLECTION);
				jvmParam.setParameterType(this.typeBuilder.cloneWithProxies(collectionType));
				operation.getParameters().add(jvmParam);

				operation.setAbstract(false);
				operation.setNative(false);
				operation.setSynchronized(false);
				operation.setStrictFloatingPoint(false);
				operation.setFinal(false);
				operation.setVisibility(JvmVisibility.PRIVATE);
				operation.setStatic(false);
				operation.setSimpleName(behName);
				operation.setReturnType(this.typeBuilder.cloneWithProxies(voidType));
				container.getMembers().add(operation);

				setBody(operation, it -> {
					it.append("assert "); //$NON-NLS-1$
					it.append(this.grammarKeywordAccess.getOccurrenceKeyword());
					it.append(" != null;"); //$NON-NLS-1$
					it.newLine();
					it.append("assert "); //$NON-NLS-1$
					it.append(RUNNABLE_COLLECTION);
					it.append(" != null;"); //$NON-NLS-1$
					for (final Procedure1<? super ITreeAppendable> code : evaluators.getValue()) {
						it.newLine();
						code.apply(it);
					}
				});

				this.associator.associatePrimary(source, operation);
				this.typeBuilder.copyDocumentationTo(source, operation);
			}
		}
	}
71183
public void run () throws Exception
  {
    if (System.getSecurityManager () != null)
      throw new IllegalStateException ("Security Manager is set but not supported - aborting!");

    final String sTempDir = SystemProperties.getTmpDir ();

    // Create main server
    final Server aServer = new Server (m_aThreadPool);
    {
      // Create connector on Port
      final ServerConnector aConnector = new ServerConnector (aServer);
      aConnector.setPort (m_nPort);
      aConnector.setIdleTimeout (30_000);
      customizeServerConnector (aConnector);
      aServer.setConnectors (new Connector [] { aConnector });
      aServer.setAttribute ("org.eclipse.jetty.server.Request.maxFormContentSize",
                            Integer.valueOf (2 * CGlobal.BYTES_PER_MEGABYTE));
      aServer.setAttribute ("org.eclipse.jetty.server.Request.maxFormKeys", Integer.valueOf (20000));
    }

    customizeServer (aServer);

    final WebAppContext aWebAppCtx = new WebAppContext ();
    {
      aWebAppCtx.setBaseResource (m_aResourceBase);
      aWebAppCtx.setDescriptor (m_sWebXmlResource != null ? m_sWebXmlResource
                                                          : m_aResourceBase.addPath ("/WEB-INF/web.xml").getName ());
      aWebAppCtx.setContextPath (m_sContextPath);
      aWebAppCtx.setTempDirectory (new File (sTempDir + '/' + m_sDirBaseName + ".webapp"));
      aWebAppCtx.setParentLoaderPriority (true);
      aWebAppCtx.setThrowUnavailableOnStartupException (true);
      if (m_sContainerIncludeJarPattern != null)
      {
        // http://www.eclipse.org/jetty/documentation/9.4.x/configuring-webapps.html#container-include-jar-pattern
        // https://github.com/eclipse/jetty.project/issues/680
        aWebAppCtx.setAttribute (WebInfConfiguration.CONTAINER_JAR_PATTERN, m_sContainerIncludeJarPattern);
      }
      if (m_sWebInfIncludeJarPattern != null)
      {
        aWebAppCtx.setAttribute (WebInfConfiguration.WEBINF_JAR_PATTERN, m_sWebInfIncludeJarPattern);
      }

      if (m_bAllowAnnotationBasedConfig)
      {
        // Important to add the AnnotationConfiguration!
        aWebAppCtx.setConfigurations (new Configuration [] { new WebInfConfiguration (),
                                                             new WebXmlConfiguration (),
                                                             new MetaInfConfiguration (),
                                                             new FragmentConfiguration (),
                                                             new AnnotationConfiguration (),
                                                             new JettyWebXmlConfiguration () });
      }
      // else leave default
    }

    // Set session store directory to passivate/activate sessions
    if (m_bSpecialSessionMgr)
    {
      final SessionHandler aHdl = new SessionHandler ();
      final FileSessionDataStore aDataStore = new FileSessionDataStore ();
      aDataStore.setStoreDir (new File (sTempDir + '/' + m_sDirBaseName + ".sessions"));
      aDataStore.setDeleteUnrestorableFiles (true);
      final DefaultSessionCache aCache = new DefaultSessionCache (aHdl);
      aCache.setSessionDataStore (aDataStore);
      aCache.setRemoveUnloadableSessions (true);
      aHdl.setSessionCache (aCache);
      aWebAppCtx.setSessionHandler (aHdl);
    }

    if (StringHelper.hasText (m_sSessionCookieName))
      aWebAppCtx.getSessionHandler ().setSessionCookie (m_sSessionCookieName);

    customizeWebAppCtx (aWebAppCtx);

    aServer.setHandler (aWebAppCtx);
    final ServletContextHandler aCtx = aWebAppCtx;

    // Setting final properties
    // Stops the server when ctrl+c is pressed (registers to
    // Runtime.addShutdownHook)
    aServer.setStopAtShutdown (true);

    if (false)
    {
      // Debug output
      aServer.setDumpBeforeStop (true);
    }

    try
    {
      // Starting shutdown listener thread
      // May fail if port is in use
      if (m_bRunStopMonitor)
        new InternalJettyStopMonitorThread (m_nStopPort, m_sStopKey, () -> aServer.stop ()).start ();

      // Starting the engines:
      aServer.start ();
      LOGGER.info ("Started Jetty" + ":" + m_nPort + ":" + m_nStopPort + " " + m_sAppName);

      // Callback
      onServerStarted (aServer);

      Runtime.getRuntime ().addShutdownHook (new Thread ( () -> {
        try
        {
          aServer.stop ();
          aServer.join ();
        }
        catch (final Exception ex)
        {
          LOGGER.error ("Exception in ShutdownHook of JettyStarter!", ex);
        }
      }));
    }
    catch (final Throwable t)
    {
      // Do not throw something here, in case some exception occurs in finally
      // code
      LOGGER.error ("Failed to start Jetty " + m_sAppName + "!", t);

      // Callback
      onServerStartFailure (aServer, t);
    }
    finally
    {
      if (aCtx.isFailed ())
      {
        LOGGER.error ("Failed to start Jetty " + m_sAppName + " - stopping server!");
        try
        {
          // Throws an Exception e.g. in log4j2 2.5
          aServer.stop ();
          LOGGER.error ("Failed to start Jetty " + m_sAppName + " - stopped server!");
        }
        catch (final Throwable t)
        {
          LOGGER.error ("Error stopping Jetty " + m_sAppName + " after startup errors!", t);
        }
      }
      else
        if (!aServer.isFailed ())
        {
          // Running the server!
          aServer.join ();
        }
    }
  }
157198
@Override
    public void onManagerEvent(ManagerEvent event)
    {

        // if this turns out to be slow, we could consider caching the reflection lookup

        try
        {

            Method method = this.getClass().getDeclaredMethod("handleEvent", new Class[]{event.getClass()});
            if (method != null)
            {
                method.invoke(this, event);
                return;
            }
        }
        catch (Exception e)
        {
            logger.error(e, e);
        }

        logger.error("The event " + event.getClass()
                + " couldn't be mapped to a method in AbstractManagerEventListener.java, someone should add it!");

    }
998148
public void init(BaseMessageManager manager, String strQueueName, String strQueueType)
    {
        super.init(manager, strQueueName, strQueueType);
    }
442330
public static void assertIOThread(Thread t, boolean flag) {
        if (flag) {
            assert t.equals(Thread.currentThread()) : "Management NOT on IO thread when expected";  // XXX testing
        } else {
            assert !(t.equals(Thread.currentThread())) : "Management on IO thread when not expected";  // XXX testing
        }
    }