<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
 def terminate(self, nowait=False):
 """Finalize and stop service Args: nowait: set to True to terminate immediately and skip processing messages still in the queue """

        logger.debug("Acquiring lock for service termination")
        with self.lock:
            logger.debug("Terminating service")

            if not self.listener:
                logger.warning("Service already stopped.")
                return

            self.listener.stop(nowait)

            try:
                if not nowait:
                    self._post_log_batch()
            except Exception:
                if self.error_handler:
                    self.error_handler(sys.exc_info())
                else:
                    raise
            finally:
                self.queue = None
                self.listener = None