chatprogramm was sonst
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

34 lines
757 B

1 year ago
  1. package server.util;
  2. /*
  3. !!! WORK IN PROGRESS !!!
  4. trying to implement a wait-free queue
  5. */
  6. import java.util.concurrent.atomic.AtomicReferenceArray;
  7. public class Queue<T> {
  8. private volatile int head = 0, tail = 0;
  9. private final int capacity;
  10. private AtomicReferenceArray<T> items;
  11. public Queue(int capacity) {
  12. this.capacity = capacity;
  13. items = new AtomicReferenceArray<>(capacity);
  14. }
  15. public boolean enq(T x) {
  16. if (tail - head == capacity) return false;
  17. items.set((tail + 1) % capacity, x);
  18. tail++;
  19. return true;
  20. }
  21. public T deq() {
  22. if (tail - head == 0) return null;
  23. T x = items.get((head + 1) % capacity);
  24. head++;
  25. return x;
  26. }
  27. }