I am doing a project on a print spooler. I am using multithreading to support multiple clients.
The problem is that I need another thread on the server side to take care of the printing by extracting jobs from a priority queue. If the queue is empty the thread must be idle and when a job comes it must service it.
How do i go about this? Where do i start the print thread? And from where do i let the thread know that a job has entered into a previously empty thread?

Dani AI

Generated

A simple, robust pattern is to start one long-lived consumer thread at server initialization that pulls print jobs from a thread-safe priority queue and blocks when there is no work. This answers s question about "where to start the print thread" and how it knows a previously empty queue has a job — the blocking retrieval call handles the waiting and wake-up for you (no manual notify required). pointed toward a blocking-queue approach; the queue choice should support priority ordering and your required tie-breaking rules.

Make job ordering explicit (priority plus a stable tiebreaker) and keep job objects immutable while queued. Example pattern:

static final AtomicLong SEQ = new AtomicLong();

class PrintJob implements Comparable<PrintJob> {
  final int priority;
  final long seq;
  PrintJob(int priority) { this.priority = priority; this.seq = SEQ.getAndIncrement(); }
  public int compareTo(PrintJob o) {
    int c = Integer.compare(o.priority, this.priority); // higher priority first
    return (c != 0) ? c : Long.compare(this.seq, o.seq); // FIFO for ties
  }
}

Run a single consumer or a fixed pool of printer threads and let take() block until work arrives:

PriorityBlockingQueue<PrintJob> queue = new PriorityBlockingQueue<>();
ExecutorService printers = Executors.newSingleThreadExecutor();

printers.execute(() -> {
  try {
    while (!Thread.currentThread().isInterrupted()) {
      PrintJob job = queue.take();
      doPrint(job);
    }
  } catch (InterruptedException e) { Thread.currentThread().interrupt(); }
});

Notes: take() blocks and wakes automatically when producers put/add jobs. Priority queues are typically unbounded — consider backpressure (a semaphore or bounded wrapper) if memory or rate control is needed. See the PriorityBlockingQueue javadoc for API details: PriorityBlockingQueue javadoc.

Recommended Answers

All 3 Replies

Use a LinkedBlockingQueue for the server - you'll find examples on the web.

Use a LinkedBlockingQueue for the server - you'll find examples on the web.

I am using a priority blocking queue. Is that alright? I need to use a priority queue!

Yes, absolutely. LinkedBlockingQueue is FIFO, I missed the bit where you said "priority", sorry.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.