Redirects messages until a shutdown message is received.
771087
def run(self):
        """"""
        while True:
            if not self.task_socket.poll(-1):
                continue

            msg = self.task_socket.recv_multipart()
            msg_type = msg[1]

            if self.debug:
                self.stats.append((time.time(),
                                   msg_type,
                                   len(self.unassigned_tasks),
                                   len(self.available_workers)))
                if time.time() - self.lastDebugTs > TIME_BETWEEN_PARTIALDEBUG:
                    self.writeDebug("debug/partial-{0}".format(
                        round(time.time(), -1)
                    ))
                    self.lastDebugTs = time.time()

            # New task inbound
            if msg_type == TASK:
                task_id = msg[2]
                task = msg[3]
                self.logger.debug("Received task {0}".format(task_id))
                try:
                    address = self.available_workers.popleft()
                except IndexError:
                    self.unassigned_tasks.append((task_id, task))
                else:
                    self.logger.debug("Sent {0}".format(task_id))
                    self.task_socket.send_multipart([address, TASK, task])
                    self.assigned_tasks[address].add(task_id)

            # Request for task
            elif msg_type == REQUEST:
                address = msg[0]
                try:
                    task_id, task = self.unassigned_tasks.popleft()
                except IndexError:
                    self.available_workers.append(address)
                else:
                    self.logger.debug("Sent {0}".format(task_id))
                    self.task_socket.send_multipart([address, TASK, task])
                    self.assigned_tasks[address].add(task_id)

            # A task status request is requested
            elif msg_type == STATUS_REQ:
                self.pruneAssignedTasks()
                address = msg[0]
                task_id = msg[2]

                if any(task_id in x for x in self.assigned_tasks.values()):
                    status = STATUS_GIVEN
                elif task_id in (x[0] for x in self.unassigned_tasks):
                    status = STATUS_HERE
                else:
                    status = STATUS_NONE

                self.task_socket.send_multipart([
                    address, STATUS_ANS, task_id, status
                ])

            # A task status set (task done) is received
            elif msg_type == STATUS_DONE:
                address = msg[0]
                task_id = msg[2]

                try:
                    self.assigned_tasks[address].discard(task_id)
                except KeyError:
                    pass

            elif msg_type == STATUS_UPDATE:
                address = msg[0]
                try:
                    tasks_ids = pickle.loads(msg[2])
                except:
                    self.logger.error("Could not unpickle status update message.")
                else:
                    self.assigned_tasks[address] = tasks_ids
                    self.status_times[address] = time.time()

            # Answer needing delivery
            elif msg_type == REPLY:
                self.logger.debug("Relaying")
                destination = msg[-1]
                origin = msg[0]
                self.task_socket.send_multipart([destination] + msg[1:] + [origin])

            # Shared variable to distribute
            elif msg_type == VARIABLE:
                address = msg[4]
                value = msg[3]
                key = msg[2]
                self.shared_variables[address].update(
                    {key: value},
                )
                self.info_socket.send_multipart([VARIABLE,
                                                key,
                                                value,
                                                address])

            # Initialize the variables of a new worker
            elif msg_type == INIT:
                address = msg[0]
                try:
                    self.processConfig(pickle.loads(msg[2]))
                except pickle.PickleError:
                    continue
                self.task_socket.send_multipart([
                    address,
                    pickle.dumps(self.config,
                                 pickle.HIGHEST_PROTOCOL),
                    pickle.dumps(self.shared_variables,
                                 pickle.HIGHEST_PROTOCOL),
                ])

                self.task_socket.send_multipart([
                    address,
                    pickle.dumps(self.cluster_available,
                                 pickle.HIGHEST_PROTOCOL),
                ])

            # Add a given broker to its fellow list
            elif msg_type == CONNECT:
                try:
                    connect_brokers = pickle.loads(msg[2])
                except pickle.PickleError:
                    self.logger.error("Could not understand CONNECT message.")
                    continue
                self.logger.info("Connecting to other brokers...")
                self.addBrokerList(connect_brokers)

            # Shutdown of this broker was requested
            elif msg_type == SHUTDOWN:
                self.logger.debug("SHUTDOWN command received.")
                self.shutdown()
                break
1142988
def shutdown(self, wait=True):
        
        self.scheduler_thread.stop()
        self.worker_message_handler_thread.stop()

        if wait:
            self.scheduler_thread.join()
            self.worker_message_handler_thread.join()
125294
def do_shutdown (self):
        """"""
        with self.mutex:
            unfinished = self.unfinished_tasks - len(self.queue)
            self.queue.clear()
            if unfinished <= 0:
                if unfinished < 0:
                    raise ValueError('shutdown is in error')
                self.all_tasks_done.notifyAll()
            self.unfinished_tasks = unfinished
            self.shutdown = True
419755
public void doShutdown() {
        long t = System.currentTimeMillis();
        LOG.info(""+name+" is going down now");
        synchronized (this){
            this.stopped = false;
            this.run = false;
        }
        while(true){
            synchronized (this){
                if(stopped)
                    break;
            }
            try {
                Thread.sleep(1);
            } catch (InterruptedException e) {
                break;
            }
        }
        LOG.info(""+name+" stopped in "+(System.currentTimeMillis()-t)+" ms.");
    }
231693
def process_messages_loop(self):
        
        self.receiving_messages = True
        try:
            self.process_messages_loop_internal()
        except pika.exceptions.ConnectionClosed as ex:
            logging.error("Connection closed {}.".format(ex))
            raise
710242
public synchronized void shutDown() {

        m_adminCms = null;

        if (CmsLog.INIT.isInfoEnabled()) {
            CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_SHUTDOWN_1, this.getClass().getName()));
        }

        if (m_scheduler != null) {
            try {
                m_scheduler.shutdown();
            } catch (SchedulerException e) {
                LOG.error(Messages.get().getBundle().key(Messages.LOG_SHUTDOWN_ERROR_0));
            }
        }

        m_scheduler = null;
    }
577314
def on_shutdown(self, broker):
        """"""
        _v and LOG.debug('%r.on_shutdown()', self)
        if not IS_WSL:
            # #333: WSL generates invalid readiness indication on shutdown()
            self._wsock.shutdown(socket.SHUT_WR)
        self._wsock.close()
        self.transmit_side.close()
574135
void waitForQueueToDrain() {
        int remainingMessages = delayableImmutableMessages.size();
        logger.info("joynr message queue stopping. Contains {} remaining messages.", remainingMessages);
        if (remainingMessages > 0) {
            long shutdownStart = System.currentTimeMillis();
            while (System.currentTimeMillis() - shutdownStart < shutdownTimeoutMs) {
                if (delayableImmutableMessages.size() == 0) {
                    break;
                }
                try {
                    Thread.sleep(5);
                } catch (InterruptedException e) {
                    logger.error("Interrupted while waiting for joynr message queue to drain.");
                    e.printStackTrace();
                }
            }
        }
        remainingMessages = delayableImmutableMessages.size();
        if (remainingMessages == 0) {
            logger.info("joynr message queue successfully emptied.");
        } else {
            logger.info("joynr message queue still contained " + remainingMessages + " messages at shutdown.");
        }
    }
458915
public synchronized void sendRetry(long retry, EventCallback callback) {

        if (open == 0 || shutdown) {
            if (callback != null) {
                callback.failed(this, null, null, null, new ClosedChannelException());
            }
            return;
        }
        queue.add(new SSEData(retry, callback));
        sink.getIoThread().execute(new Runnable() {
            @Override
            public void run() {
                synchronized (ServerSentEventConnection.this) {
                    if (pooled == null) {
                        fillBuffer();
                        writeListener.handleEvent(sink);
                    }
                }
            }
        });
    }
776044
def pause(self):
        
        msg = cr.Message()
        msg.type = cr.PAUSE
        self.send_message(msg)
1312321
void shutdown() {
        m_isShutdown = true;
        try {
            int waitFor = 1 - Math.min(m_inFlight.availablePermits(), -4);
            for (int i = 0; i < waitFor; ++i) {
                try {
                    if (m_inFlight.tryAcquire(1, TimeUnit.SECONDS)) {
                        m_inFlight.release();
                        break;
                    }
                } catch (InterruptedException e) {
                    break;
                }
            }

            m_ecryptgw.die();

            EncryptFrame frame = null;
            while ((frame = m_encryptedFrames.poll()) != null) {
                frame.frame.release();
            }

            for (EncryptFrame ef: m_partialMessages) {
                ef.frame.release();
            }
            m_partialMessages.clear();

            if (m_encryptedMessages.refCnt() > 0) m_encryptedMessages.release();
        } finally {
            m_inFlight.drainPermits();
            m_inFlight.release();
        }
    }
252670
protected final void awaitShutdown() throws InterruptedException {
		Runtime.getRuntime().addShutdownHook(new Thread(() -> {
			try {
				shutdown();
				finishLatch.await();
				Thread.sleep(10); // wait a bit for things outside `launch` call, such as JUnit finishing or whatever
			} catch (InterruptedException e) {
				logger.error("Shutdown took too long", e);
			}
		}, "shutdownNotification"));
		shutdownLatch.await();
	}
1054948
def finish(self):
        ''

        self.finished = True
        self.update(self.maxval)
        self.fd.write('\n')
        if self.signal_set:
            signal.signal(signal.SIGWINCH, signal.SIG_DFL)

        if self.redirect_stderr:
            self._stderr.write(sys.stderr.getvalue())
            sys.stderr = self._stderr

        if self.redirect_stdout:
            self._stdout.write(sys.stdout.getvalue())
            sys.stdout = self._stdout
930380
def shutdown
      raise MailboxDead, "mailbox already shutdown" if @dead

      @mutex.lock
      begin
        yield if block_given?
        messages = @messages
        @messages = []
        @dead = true
      ensure
        begin
          @mutex.unlock
        rescue
          nil
        end
      end

      messages.each do |msg|
        dead_letter msg
        msg.cleanup if msg.respond_to? :cleanup
      end
      true
    end
23404
public void shutdown() {
        if (clientList == null) {
            return;
        }
        cancelEvictor();
        for (RedisClient connection : clientList) {
            try {
                connection.shutdown();
            } catch (Exception e) {
                logger.debug(e.getMessage(), e);
            }
        }
    }
1269708
def on_message_received(self, msg):
        
        if self.is_stopped:
            raise RuntimeError("reader has already been stopped")
        else:
            self.buffer.put(msg)
1174798
public void handleMessage (Message message)
    {
        // if the client has been getting crazy with the cheeze whiz, stick a fork in them; the
        // first time through we end our session, subsequently _throttle is null and we just drop
        // any messages that come in until we've fully shutdown
        if (_throttle == null) {
//             log.info("Dropping message from force-quit client", "conn", getConnection(),
//                      "msg", message);
            return;

        } else if (_throttle.throttleOp(message.received)) {
            handleThrottleExceeded();
        }

        dispatchMessage(message);
    }