This must run ON the IO thread
193649
@Override
    public void doSessionCreated(final long sessionId, final ManagementSessionType managementSessionType) throws Exception {
        ThreadGatewayStats stats = gatewayStats.get();
        stats.doSessionCreated();
    }
699804
def run(self, target, args=()):
        
        run_event = threading.Event()
        run_event.set()
        thread = threading.Thread(target=target, args=args + (run_event, ))
        self.thread_pool.append(thread)
        self.run_events.append(run_event)
        thread.start()
1061991
def run(self):
        

        self._systemd_notify_once()
        self._child_supervisor = _utils.spawn(self._child_supervisor_thread)
        self._wait_forever()
625120
def run_in_executor(self, callback):
        
        # Wait until the main thread is idle.
        # We start the thread by using `call_from_executor`. The event loop
        # favours processing input over `calls_from_executor`, so the thread
        # will not start until there is no more input to process and the main
        # thread becomes idle for an instant. This is good, because Python
        # threading favours CPU over I/O -- an autocompletion thread in the
        # background would cause a significantly slow down of the main thread.
        # It is mostly noticable when pasting large portions of text while
        # having real time autocompletion while typing on.
        def start_executor():
            threading.Thread(target=callback).start()
        self.call_from_executor(start_executor)
1203280
def run(self):
        """"""
        self.running = True
        while self.running:
            for fd, event in self.epoll.poll(self.epoll_timeout):
                callback = self.callbacks.get(fd)
                if callback:
                    callback()
1047038
public void run() {
        // Unique nr that identifies this request.
        int thisRequest = compilerPool.startRequest();
        long start = System.currentTimeMillis();
        int numClasses = 0;
        StringBuilder compiledPkgs = new StringBuilder();
        use();

        PrintWriter out = null;
        try {
            javacServer.log("<"+thisRequest+"> Connect from "+socket.getRemoteSocketAddress()+" activethreads="+compilerPool.numActiveRequests());
            BufferedReader in = new BufferedReader(new InputStreamReader(
                                                       socket.getInputStream()));
            out = new PrintWriter(new OutputStreamWriter(
                                                  socket.getOutputStream()));
            if (!expect(in, JavacServer.PROTOCOL_COOKIE_VERSION)) {
                javacServer.log("<"+thisRequest+"> Bad protocol from ip "+socket.getRemoteSocketAddress());
                return;
            }

            String cookie = in.readLine();
            if (cookie == null || !cookie.equals(""+javacServer.getCookie())) {
                javacServer.log("<"+thisRequest+"> Bad cookie from ip "+socket.getRemoteSocketAddress());
                return;
            }
            if (!expect(in, JavacServer.PROTOCOL_CWD)) {
                return;
            }
            String cwd = in.readLine();
            if (cwd == null)
                return;
            if (!expect(in, JavacServer.PROTOCOL_ID)) {
                return;
            }
            id = in.readLine();
            if (id == null)
                return;
            if (!expect(in, JavacServer.PROTOCOL_ARGS)) {
                return;
            }
            ArrayList<String> the_options = new ArrayList<String>();
            ArrayList<File> the_classes = new ArrayList<File>();
            Iterable<File> path = Arrays.<File> asList(new File(cwd));

            for (;;) {
                String l = in.readLine();
                if (l == null)
                    return;
                if (l.equals(JavacServer.PROTOCOL_SOURCES_TO_COMPILE))
                    break;
                if (l.startsWith("--server:"))
                    continue;
                if (!l.startsWith("-") && l.endsWith(".java")) {
                    the_classes.add(new File(l));
                    numClasses++;
                } else {
                    the_options.add(l);
                }
                continue;
            }

            // Load sources to compile
            Set<URI> sourcesToCompile = new HashSet<URI>();
            for (;;) {
                String l = in.readLine();
                if (l == null)
                    return;
                if (l.equals(JavacServer.PROTOCOL_VISIBLE_SOURCES))
                    break;
                try {
                    sourcesToCompile.add(new URI(l));
                    numClasses++;
                } catch (URISyntaxException e) {
                    return;
                }
            }
            // Load visible sources
            Set<URI> visibleSources = new HashSet<URI>();
            boolean fix_drive_letter_case =
                StringUtils.toLowerCase(System.getProperty("os.name")).startsWith("windows");
            for (;;) {
                String l = in.readLine();
                if (l == null)
                    return;
                if (l.equals(JavacServer.PROTOCOL_END))
                    break;
                try {
                    URI u = new URI(l);
                    if (fix_drive_letter_case) {
                        // Make sure the driver letter is lower case.
                        String s = u.toString();
                        if (s.startsWith("file:/") &&
                            Character.isUpperCase(s.charAt(6))) {
                            u = new URI("file:/"+Character.toLowerCase(s.charAt(6))+s.substring(7));
                        }
                    }
                    visibleSources.add(u);
                } catch (URISyntaxException e) {
                    return;
                }
            }

            // A completed request has been received.

            // Now setup the actual compilation....
            // First deal with explicit source files on cmdline and in at file.
            com.sun.tools.javac.util.ListBuffer<JavaFileObject> compilationUnits =
                new com.sun.tools.javac.util.ListBuffer<JavaFileObject>();
            for (JavaFileObject i : fileManager.getJavaFileObjectsFromFiles(the_classes)) {
                compilationUnits.append(i);
            }
            // Now deal with sources supplied as source_to_compile.
            com.sun.tools.javac.util.ListBuffer<File> sourcesToCompileFiles =
                new com.sun.tools.javac.util.ListBuffer<File>();
            for (URI u : sourcesToCompile) {
                sourcesToCompileFiles.append(new File(u));
            }
            for (JavaFileObject i : fileManager.getJavaFileObjectsFromFiles(sourcesToCompileFiles)) {
                compilationUnits.append(i);
            }
            // Log the options to be used.
            StringBuilder options = new StringBuilder();
            for (String s : the_options) {
                options.append(">").append(s).append("< ");
            }
            javacServer.log(id+" <"+thisRequest+"> options "+options.toString());

            forcedExitCode = 0;
            // Create a new logger.
            StringWriter stdoutLog = new StringWriter();
            StringWriter stderrLog = new StringWriter();
            stdout = new PrintWriter(stdoutLog);
            stderr = new PrintWriter(stderrLog);
            com.sun.tools.javac.main.Main.Result rc = com.sun.tools.javac.main.Main.Result.OK;
            try {
                if (compilationUnits.size() > 0) {
                    // Bind the new logger to the existing context.
                    context.put(Log.outKey, stderr);
                    Log.instance(context).setWriter(Log.WriterKind.NOTICE, stdout);
                    Log.instance(context).setWriter(Log.WriterKind.WARNING, stderr);
                    Log.instance(context).setWriter(Log.WriterKind.ERROR, stderr);
                    // Process the options.
                    com.sun.tools.javac.api.JavacTool.processOptions(context, smartFileManager, the_options);
                    fileManagerBase.setContext(context);
                    smartFileManager.setVisibleSources(visibleSources);
                    smartFileManager.cleanArtifacts();
                    smartFileManager.setLog(stdout);
                    Dependencies.instance(context).reset();

                    com.sun.tools.javac.main.Main ccompiler = new com.sun.tools.javac.main.Main("javacTask", stderr);
                    String[] aa = the_options.toArray(new String[0]);

                    // Do the compilation!
                    rc = ccompiler.compile(aa, context, compilationUnits.toList(), null);

                    while (numActiveSubTasks()>0) {
                        try { Thread.sleep(1000); } catch (InterruptedException e) { }
                    }

                    smartFileManager.flush();
                }
            } catch (Exception e) {
                stderr.println(e.getMessage());
                forcedExitCode = -1;
            }

            // Send the response..
            out.println(JavacServer.PROTOCOL_STDOUT);
            out.print(stdoutLog);
            out.println(JavacServer.PROTOCOL_STDERR);
            out.print(stderrLog);
            // The compilation is complete! And errors will have already been printed on out!
            out.println(JavacServer.PROTOCOL_PACKAGE_ARTIFACTS);
            Map<String,Set<URI>> pa = smartFileManager.getPackageArtifacts();
            for (String aPkgName : pa.keySet()) {
                out.println("+"+aPkgName);
                Set<URI> as = pa.get(aPkgName);
                for (URI a : as) {
                    out.println(" "+a.toString());
                }
            }
            Dependencies deps = Dependencies.instance(context);
            out.println(JavacServer.PROTOCOL_PACKAGE_DEPENDENCIES);
            Map<String,Set<String>> pd = deps.getDependencies();
            for (String aPkgName : pd.keySet()) {
                out.println("+"+aPkgName);
                Set<String> ds = pd.get(aPkgName);
                    // Everything depends on java.lang
                    if (!ds.contains(":java.lang")) ds.add(":java.lang");
                for (String d : ds) {
                    out.println(" "+d);
                }
            }
            out.println(JavacServer.PROTOCOL_PACKAGE_PUBLIC_APIS);
            Map<String,String> pp = deps.getPubapis();
            for (String aPkgName : pp.keySet()) {
                out.println("+"+aPkgName);
                String ps = pp.get(aPkgName);
                // getPubapis added a space to each line!
                out.println(ps);
                compiledPkgs.append(aPkgName+" ");
            }
            out.println(JavacServer.PROTOCOL_SYSINFO);
            out.println("num_cores=" + Runtime.getRuntime().availableProcessors());
            out.println("max_memory=" + Runtime.getRuntime().maxMemory());
            out.println(JavacServer.PROTOCOL_RETURN_CODE);

            // Errors from sjavac that affect compilation status!
            int rcv = rc.exitCode;
            if (rcv == 0 && forcedExitCode != 0) {
                rcv = forcedExitCode;
            }
            out.println("" + rcv);
            out.println(JavacServer.PROTOCOL_END);
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) out.close();
                if (!socket.isClosed()) {
                    socket.close();
                }
                socket = null;
            } catch (Exception e) {
                javacServer.log("ERROR "+e);
                e.printStackTrace();
            }
            compilerPool.stopRequest();
            long duration = System.currentTimeMillis()-start;
            javacServer.addBuildTime(duration);
            float classpersec = ((float)numClasses)*(((float)1000.0)/((float)duration));
            javacServer.log(id+" <"+thisRequest+"> "+compiledPkgs+" duration " + duration+ " ms    num_classes="+numClasses+
                             "     classpersec="+classpersec+" subtasks="+subTasks.size());
            javacServer.flushLog();
            unuse();
            compilerPool.returnCompilerThread(this);
        }
    }
99671
public void run() {
        while (true) {
            Object obj;
            try {
                obj = messages.take();
                notifySubscribers(obj);
            } catch (InterruptedException e) {
                // restore interrupted status
                Thread.currentThread().interrupt();
            }
        }
    }
289584
def run(self):
        
        self.main_task.thread.start()
        self.main_task.thread.join()
126711
public void run() {
    try {
      while (!stop) {
        while (is.available() > 0 && !stop) {
          os.write(is.read());
        }
        os.flush();
        Thread.sleep(SLEEPING_TIME);
      }
    }
    catch (Exception e) {
      log.error("Got exception while reading/writing the stream", e);
    }
  }
1093826
public void run() {
    log.trace("{} started.", this);
    synchronized (this) {
      // Just in case this object is reused in the future
      finished = false;
    }

    final byte[] buf = new byte[this.size];

    int length;
    try {
      while ((length = is.read(buf)) > 0) {
        os.write(buf, 0, length);
        if(flushImmediately) {
        	os.flush();
        }
      }
    } catch (Exception e) {
      // nothing to do - happens quite often with watchdog
    } finally {
      log.trace("{} finished.", this);
      if (closeWhenExhausted) {
        try {
          os.close();
        } catch (IOException e) {
          log.error("Got exception while closing exhausted output stream", e);
        }
      }
      synchronized (this) {
        finished = true;
        notifyAll();
      }
    }
  }
99060
public void run() {
        try {
            mServer = new ServerSocket(mPort, VIEW_SERVER_MAX_CONNECTIONS, InetAddress.getLocalHost());
        } catch (Exception e) {
            Log.w(LOG_TAG, "Starting ServerSocket error: ", e);
        }

        while (mServer != null && Thread.currentThread() == mThread) {
            // Any uncaught exception will crash the system process
            try {
                Socket client = mServer.accept();
                if (mThreadPool != null) {
                    mThreadPool.submit(new ViewServerWorker(client));
                } else {
                    try {
                        client.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            } catch (Exception e) {
                Log.w(LOG_TAG, "Connection error: ", e);
            }
        }
    }
981426
public void run() {

        while (!stop) {
            try {
                //  Poll the sockets inputs
                pollers.poll();

                //  read the speaking one
                for (int i=0 ; i<pollers.getSize() ; i++) {
                    if (pollers.pollin(i)) {
                        manageInputBuffer(i);
                    }
                }
            }
            catch (Error | Exception e) {
                e.printStackTrace();
            }
        }
        ApiUtil.printTrace("------------ End of ZmqMainThread ---------------");
    }
936536
def run(self):
        """"""
        executor = concurrent.futures.ThreadPoolExecutor(max_workers=1)
        loop = asyncio.get_event_loop()
        loop.run_until_complete(self._run_loop(executor))
        self._log.info('Shutting down...')
        executor.shutdown()
1193102
public final void run() {
        int partitionCount = partitionService.getPartitionCount();
        latch = new CountDownLatch(partitionCount);

        for (int partitionId = 0; partitionId < partitionCount; partitionId++) {
            operationExecutor.execute(new CollectContainerRunnable(partitionId));
        }

        try {
            latch.await();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
231574
def start(self, threaded=True):
        
        self.running = True
        if threaded:
            self._thread = Thread(target=self._run)
            self._thread.start()
        else:
            self._run()
347860
def run(self):
        """"""
        # Catch all possible exceptions raised by the running thread
        # and let parent process know about it.
        try:
            self._run()
        except Exception:  # pylint: disable=broad-except
            self.action.put(
                ServiceCheckDiedError(self.name, traceback.format_exc())
            )
1007631
def run(self):
        """"""
        event_handler = Handler()
        threads = []
        paths = [os.path.join(cwd, "content"), os.path.join(cwd, "templates")]

        for i in paths:
            targetPath = str(i)
            self.observer.schedule(event_handler, targetPath, recursive=True)
            threads.append(self.observer)

        self.observer.start()

        try:
            while True:
                time.sleep(5)
        except:
            self.observer.stop()
            print("\nObserver stopped.")

        self.observer.join()