Untitled


SUBMITTED BY: antoineh1

DATE: May 8, 2016, 2:01 p.m.

FORMAT: Text only

SIZE: 1.2 kB

HITS: 5663

  1. package ru.nsu.fit.evtushenko.storage;
  2. import java.util.LinkedList;
  3. import java.util.Observable;
  4. import java.util.Queue;
  5. public class Storage<T> extends Observable implements BlockingQueue<T> {
  6. private final int capacity;
  7. private final Object monitor = new Object();
  8. private final Queue<T> queue = new LinkedList<>();
  9. public Storage(int capacity) {
  10. this.capacity = capacity;
  11. }
  12. public Storage() {
  13. this.capacity = Integer.MAX_VALUE;
  14. }
  15. @Override
  16. public void add(T toAdd) throws InterruptedException {
  17. synchronized (monitor) {
  18. while (true) {
  19. if (queue.size() < capacity) {
  20. queue.add(toAdd);
  21. monitor.notifyAll();
  22. setChanged();
  23. notifyObservers(queue.size());
  24. return;
  25. } else {
  26. monitor.wait();
  27. }
  28. }
  29. }
  30. }
  31. @Override
  32. public T get() throws InterruptedException {
  33. synchronized (monitor) {
  34. while (true) {
  35. if (!queue.isEmpty()) {
  36. monitor.notifyAll();
  37. T result = queue.remove();
  38. setChanged();
  39. notifyObservers(queue.size());
  40. return result;
  41. } else {
  42. monitor.wait();
  43. }
  44. }
  45. }
  46. }
  47. @Override
  48. public int getSize() {
  49. synchronized (monitor) {
  50. return queue.size();
  51. }
  52. }
  53. }

comments powered by Disqus