Advertisement
Guest User

Untitled

a guest
Nov 18th, 2018
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.58 KB | None | 0 0
  1. package storage;
  2.  
  3. import storage.administration.CargoHolder;
  4. import storage.cargo.Cargo;
  5.  
  6. import java.util.concurrent.locks.Condition;
  7. import java.util.concurrent.locks.Lock;
  8. import java.util.concurrent.locks.ReentrantLock;
  9.  
  10. public class StorageImplementation implements Storage {
  11. private CargoHolder cargoHolder;
  12. private final Lock lock = new ReentrantLock();
  13. private final Condition full = this.lock.newCondition();
  14. private final Condition empty = this.lock.newCondition();
  15. private boolean isFull;
  16. private boolean isEmpty;
  17.  
  18. // private boolean isFull() {
  19. // return null != this.cargoHolder;
  20. // }
  21.  
  22. public StorageImplementation(int cargoHolderSize){
  23. cargoHolder = new CargoHolder(cargoHolderSize);
  24.  
  25. }
  26.  
  27. @Override
  28. public void put(Cargo cargo) throws InterruptedException {
  29. this.lock.lock();
  30. try {
  31. if (isFull)
  32. this.empty.await();
  33.  
  34. while (true) {
  35.  
  36. if (!cargoHolder.add(cargo)) {
  37. isFull = true;
  38. this.empty.await();
  39.  
  40. } else
  41. System.out.println("Loading!");
  42.  
  43. break;
  44.  
  45. }
  46.  
  47. isEmpty = false;
  48. this.full.signal();
  49.  
  50. }
  51. /*}catch (InterruptedException e){ throw e;*/ finally {
  52. this.lock.unlock();
  53. }
  54. }
  55.  
  56. @Override
  57. public void moveOldestCargoToOtherStorage(Storage storage) throws InterruptedException {
  58. this.lock.lock();
  59. try {
  60. if (isEmpty)
  61. this.full.await();
  62. while (true) {
  63. Cargo cargo = cargoHolder.removeCargoByIndex(0);
  64. if (null == cargo) {
  65. isEmpty = true;
  66. this.full.await();
  67.  
  68. } else {
  69. storage.put(cargo);
  70. //if (!storage.put(cargo))
  71.  
  72. System.out.println("Moving to storage");
  73. break;
  74. }
  75. }
  76. isFull = false;
  77. this.empty.signal();
  78.  
  79. }
  80. /*}catch (InterruptedException e){ throw e;*/ finally {
  81. this.lock.unlock();
  82. }
  83. }
  84.  
  85. // public static void main(String[] args) {
  86. // Storage storage = new StorageImpl();
  87. // for (int i = 0; i < 100; i++)
  88. // new Producer(storage).start();
  89. // for (int i = 0; i < 100; i++)
  90. // new Consumer(storage).start();
  91. // }
  92.  
  93.  
  94. public boolean isFull() {
  95. return isFull;
  96. }
  97. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement