-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTaskQueue.java
More file actions
43 lines (36 loc) · 1.24 KB
/
TaskQueue.java
File metadata and controls
43 lines (36 loc) · 1.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package com.taskscheduler;
import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.TimeUnit;
/**
* Thread-safe priority queue for tasks.
* Higher priority tasks are dequeued before lower priority ones.
*/
public class TaskQueue {
private final PriorityBlockingQueue<Task> queue;
private final int capacity;
public TaskQueue(int capacity) {
this.capacity = capacity;
this.queue = new PriorityBlockingQueue<>(capacity);
}
/**
* Add a task to the queue. Returns false if at capacity.
*/
public boolean submit(Task task) {
if (queue.size() >= capacity) {
System.err.println("[TaskQueue] Queue full! Rejecting: " + task);
return false;
}
queue.offer(task);
System.out.printf("[TaskQueue] Submitted %s (queue size: %d)%n", task, queue.size());
return true;
}
/**
* Blocks until a task is available or timeout is reached.
*/
public Task poll(long timeout, TimeUnit unit) throws InterruptedException {
return queue.poll(timeout, unit);
}
public int size() { return queue.size(); }
public boolean isEmpty(){ return queue.isEmpty(); }
public int getCapacity(){ return capacity; }
}