Attach listeners and execute a slave process.
968576
private void executeSlave(final ForkedJvmInfo slave, final EventBus aggregatedBus)
    throws Exception
  {
    final String uniqueSeed = new SimpleDateFormat("yyyyMMdd_HHmmss_SSS", Locale.ROOT).format(new Date());

    final Path classNamesFile = tempFile(uniqueSeed, "junit4-J" + slave.id, ".suites", getTempDir());
    temporaryFiles.add(classNamesFile);

    final Path classNamesDynamic = tempFile(uniqueSeed, "junit4-J" + slave.id, ".dynamic-suites", getTempDir());
    final Path streamsBufferFile = tempFile(uniqueSeed, "junit4-J" + slave.id, ".spill", getTempDir());

    // Dump all test class names to a temporary file.
    String testClassPerLine = Joiner.on("\n").join(slave.testSuites);
    log("Test class names:\n" + testClassPerLine, Project.MSG_VERBOSE);
    Files.write(classNamesFile, testClassPerLine.getBytes(StandardCharsets.UTF_8));

    // Prepare command line for java execution.
    CommandlineJava commandline;
    commandline = (CommandlineJava) getCommandline().clone();
    commandline.createClasspath(getProject()).add(addSlaveClasspath());
    commandline.setClassname(SlaveMainSafe.class.getName());
    if (slave.slaves == 1) {
      commandline.createArgument().setValue(SlaveMain.OPTION_FREQUENT_FLUSH);
    }

    // Set up full output files.
    Path sysoutFile = tempFile(uniqueSeed,
        "junit4-J" + slave.id, ".sysout", getTempDir());
    Path syserrFile = tempFile(uniqueSeed,
        "junit4-J" + slave.id, ".syserr", getTempDir());

    // Set up communication channel.
    Path eventFile = tempFile(uniqueSeed, "junit4-J" + slave.id, ".events", getTempDir());
    temporaryFiles.add(eventFile);
    commandline.createArgument().setValue(SlaveMain.OPTION_EVENTSFILE);
    commandline.createArgument().setFile(eventFile.toFile());
    
    if (sysouts) {
      commandline.createArgument().setValue(SlaveMain.OPTION_SYSOUTS);
    }
    
    if (debugStream) {
      commandline.createArgument().setValue(SlaveMain.OPTION_DEBUGSTREAM);
    }

    TailInputStream eventStream = new TailInputStream(eventFile);

    // Process user-defined RunListener classes.
    if (!runListeners.isEmpty()) {
      String classNames = runListeners.stream().map(x -> x.getClassName()).collect(Collectors.joining(","));

      commandline.createArgument().setValue(SlaveMain.OPTION_RUN_LISTENERS);
      commandline.createArgument().setValue(classNames);
    }

    // Set up input suites file.
    commandline.createArgument().setValue("@" + classNamesFile.toAbsolutePath().normalize());

    // May or may not use dynamic load balancing, but if == 0 then we're for sure
    // not using it.
    if (dynamicAssignmentRatio > 0) {
      commandline.createArgument().setValue(SlaveMain.OPTION_STDIN);
    }

    final EventBus eventBus = new EventBus("slave-" + slave.id);
    final DiagnosticsListener diagnosticsListener = new DiagnosticsListener(slave, this);
    eventBus.register(diagnosticsListener);
    eventBus.register(new AggregatingListener(aggregatedBus, slave));

    final AtomicReference<Charset> clientCharset = new AtomicReference<Charset>();
    final AtomicBoolean clientWithLimitedCharset = new AtomicBoolean(); 
    final PrintWriter w = new PrintWriter(Files.newBufferedWriter(classNamesDynamic, StandardCharsets.UTF_8));
    eventBus.register(new Object() {
      @Subscribe
      public void onIdleSlave(final SlaveIdle idleSlave) {
        aggregatedBus.post(new SlaveIdle() {
          @Override
          public void finished() {
            idleSlave.finished();
          }

          @Override
          public void newSuite(String suiteName) {
            if (!clientCharset.get().newEncoder().canEncode(suiteName)) {
              clientWithLimitedCharset.set(true);
              log("Forked JVM J" + slave.id + " skipped suite (cannot encode suite name in charset " +
                  clientCharset.get() + "): " + suiteName, Project.MSG_WARN);
              return;
            }

            log("Forked JVM J" + slave.id + " stole suite: " + suiteName, Project.MSG_VERBOSE);
            w.println(suiteName);
            w.flush();
            idleSlave.newSuite(suiteName);
          }
        });
      }

      @Subscribe
      public void onBootstrap(final BootstrapEvent e) {
        Charset cs = Charset.forName(((BootstrapEvent) e).getDefaultCharsetName());
        clientCharset.set(cs);

        slave.start = System.currentTimeMillis();
        slave.setBootstrapEvent(e);
        aggregatedBus.post(new ChildBootstrap(slave));
      }

      @Subscribe
      public void receiveQuit(QuitEvent e) {
        slave.end = System.currentTimeMillis();
      }      
    });

    Closer closer = Closer.create();
    closer.register(eventStream);
    closer.register(w);
    try {
      OutputStream sysout = closer.register(new BufferedOutputStream(Files.newOutputStream(sysoutFile)));
      OutputStream syserr = closer.register(new BufferedOutputStream(Files.newOutputStream(syserrFile)));
      RandomAccessFile streamsBuffer = closer.register(new RandomAccessFile(streamsBufferFile.toFile(), "rw"));

      Execute execute = forkProcess(slave, eventBus, commandline, eventStream, sysout, syserr, streamsBuffer);
      log("Forked JVM J" + slave.id + " finished with exit code: " + execute.getExitValue(), Project.MSG_DEBUG);

      if (execute.isFailure()) {
        final int exitStatus = execute.getExitValue();
        switch (exitStatus) {
          case SlaveMain.ERR_NO_JUNIT:
            throw new BuildException("Forked JVM's classpath must include a junit4 JAR.");
          case SlaveMain.ERR_OLD_JUNIT:
            throw new BuildException("Forked JVM's classpath must use JUnit 4.10 or newer.");
          default:
            Closeables.close(sysout, false);
            Closeables.close(syserr, false);

            StringBuilder message = new StringBuilder();
            if (exitStatus == SlaveMain.ERR_OOM) {
              message.append("Forked JVM ran out of memory.");
            } else {
              message.append("Forked process returned with error code: ").append(exitStatus).append(".");
            }

            if (Files.size(sysoutFile) > 0 || Files.size(syserrFile) > 0) {
              if (exitStatus != SlaveMain.ERR_OOM) {
                message.append(" Very likely a JVM crash. ");
              }

              if (jvmOutputAction.contains(JvmOutputAction.PIPE)) {
                message.append(" Process output piped in logs above.");
              } else if (!jvmOutputAction.contains(JvmOutputAction.IGNORE)) {
                if (Files.size(sysoutFile) > 0) {
                  message.append(" See process stdout at: " + sysoutFile.toAbsolutePath());
                }
                if (Files.size(syserrFile) > 0) {
                  message.append(" See process stderr at: " + syserrFile.toAbsolutePath());
                }
              }
            }
            throw new BuildException(message.toString());
        }
      }
    } catch (Throwable t) {
      throw closer.rethrow(t);
    } finally {
      try {
        closer.close();
      } finally {
        com.google.common.io.Files.asByteSource(classNamesDynamic.toFile())
          .copyTo(com.google.common.io.Files.asByteSink(classNamesFile.toFile(), FileWriteMode.APPEND));
        Files.delete(classNamesDynamic);
        Files.delete(streamsBufferFile);

        // Check sysout/syserr lengths.
        checkJvmOutput(aggregatedBus, sysoutFile, slave, "stdout");
        checkJvmOutput(aggregatedBus, syserrFile, slave, "stderr");        
      }
    }

    if (!diagnosticsListener.quitReceived()) {
      throw new BuildException("Quit event not received from the forked process? This may indicate JVM crash or runner bugs.");
    }

    if (clientWithLimitedCharset.get() && dynamicAssignmentRatio > 0) {
      throw new BuildException("Forked JVM J" + slave.id + " was not be able to decode class names when using" +
          " charset: " + clientCharset + ". Do not use " +
          "dynamic suite balancing to work around this problem (-DdynamicAssignmentRatio=0).");
    }
  }
865609
private void deliverSyncCommand(byte command) {
        for (final SyncListener listener : getSyncListeners()) {
            try {
                switch (command) {

                    case 0x01:
                        listener.becomeMaster();

                    case 0x10:
                       listener.setSyncMode(true);
                       break;

                    case 0x20:
                        listener.setSyncMode(false);
                        break;

                }
            } catch (Throwable t) {
                logger.warn("Problem delivering sync command to listener", t);
            }
        }
    }
785122
public synchronized void executeTaskWithUnifiedListener(@NonNull DownloadTask task,
                                                            @NonNull DownloadListener listener) {
        attachListener(task, listener);

        task.execute(hostListener);
    }
186836
function execute() {
        var listeners,
            async = isAsync(bench);

        if (async) {
          // Use `getNext` as the first listener.
          bench.on('complete', getNext);
          listeners = bench.events.complete;
          listeners.splice(0, 0, listeners.pop());
        }
        // Execute method.
        result[index] = _.isFunction(bench && bench[name]) ? bench[name].apply(bench, args) : undefined;
        // If synchronous return `true` until finished.
        return !async && getNext();
      }
1268498
@Override
	public void run()
	{
		try
		{
			while (!stopRequired)
			{
				if (traceEnabled)
					log.trace("Thread entering passive wait : "+getName());
				
				// Passive wait
				waitLock.acquire();
				if (stopRequired)
					break;
				
				// Process the container
				if (traceEnabled)
					log.trace("Executing task "+task);

				// Execute task
				task.execute();
				
				// Notify listener
				listener.executionComplete(this);
			}
		}
		catch (Throwable ex)
		{
			log.error("Asynchronous execution thread failed",ex);
		}
		log.debug("Thread exits : "+getName());
	}
630154
protected void notifyListeners()
   {
      synchronized (listeners)
      {
         Thread notifier = new NotifyThread(listeners.toArray(new BackupJobListener[listeners.size()]), this);
         notifier.start();
      }
   }
462898
def __start(self):  # pragma: no cover
        """"""

        assert not self._listener_thread

        self._listener_thread = threading.Thread(target=self.__run_listener,
                                                 name='clearly-listener')
        self._listener_thread.daemon = True
        self._listener_thread.start()
        self._wait_event.wait()
        self._wait_event.clear()
1033179
def listener(self):
        """"""
        while 1:
            try:
                data = self.read_eager()
            except EOFError:
                print('*** Connection closed by remote host ***')
                return
            if data:
                self.stdout.write(data)
            else:
                self.stdout.flush()
1006778
def execute(self, *args, **kwargs):
        
        args = self.parser.parse_args(*args, **kwargs)
        self.process(args)
990684
function onLauncherConnect(slaveURL) {
    var browsers = attester.config["run-browser"];
    if (browsers) {
        if (!Array.isArray(browsers)) {
            browsers = [browsers];
        }
        var args = [slaveURL];
        for (var i = 0, l = browsers.length; i < l; i++) {
            var curProcess = spawn(browsers[i], args, {
                stdio: "pipe"
            });
            curProcess.stdout.pipe(process.stdout);
            curProcess.stderr.pipe(process.stderr);
        }
    }
}
1187247
private static void executeListener(Runnable runnable, Executor executor, boolean maskExecutorExceptions) {
    try {
      executor.execute(runnable);
    } catch (RuntimeException e) {
        if (!maskExecutorExceptions) {
            // Caller wants to handle those exceptions
            throw e;
        }
        // Log it and keep going -- bad runnable and/or executor. Don't punish the other runnables if
        // we're given a bad one. We only catch RuntimeException because we want Errors to propagate
        // up.
        log.log(
                Level.SEVERE,
                "RuntimeException while executing runnable " + runnable + " with executor " + executor,
                e);
    }
  }
601638
private void fireUpdated(Object source) {
		for (int i=0;i<listeners.size();i++) {
			((InputPanelListener) listeners.get(i)).valueUpdated(this);
		}
	}
786996
protected function registerListeners()
    {
        $this->process->getDispatcher()->addListener(LogEvent::EVENT_NAME, function (LogEvent $event) {
            $this->data = $event->toArray();
            $this->stream();
        });
    }
302715
void fireUpdated(Object source) {
		if (updateDisable) {
			return;
		}
		
		if (source == maxSpinner) {
			if (getMax() < getMin()) {
				setMin(getMax());
			}
		}
		if (source == minSpinner) {
			if (getMax() < getMin()) {
				setMax(getMin());
			}
		}
		
		for (int i=0;i<listeners.size();i++) {
			((InputPanelListener) listeners.get(i)).minMaxUpdated(this);
		}
	}
736068
protected void fireActionPerformed ()
    {
        // guaranteed to return a non-null array
        Object[] listeners = listenerList.getListenerList();
        // process the listeners last to first, notifying those that are
        // interested in this event
        for (int i = listeners.length-2; i >= 0; i -= 2) {
            if (listeners[i] == ActionListener.class) {
                // lazily create the event:
                if (_actionEvent == null) {
                    _actionEvent = new ActionEvent(
                        this, ActionEvent.ACTION_PERFORMED, _actionCommand);
                }
                ((ActionListener)listeners[i+1]).actionPerformed(_actionEvent);
            }
        }
    }
591591
def listen():
        """"""
        msg = MSG()
        ctypes.windll.user32.GetMessageA(ctypes.byref(msg), 0, 0, 0)
989494
protected void fireSourceUpdated(S e) {
        for (int i = 0, n = this.listenerList.size(); i < n; i++) {
            this.listenerList.get(i).sourceUpdated(e);
        }
    }