Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package storage;
- import storage.administration.CargoHolder;
- import storage.cargo.Cargo;
- import java.util.concurrent.locks.Condition;
- import java.util.concurrent.locks.Lock;
- import java.util.concurrent.locks.ReentrantLock;
- public class StorageImplementation implements Storage {
- private CargoHolder cargoHolder;
- private final Lock lock = new ReentrantLock();
- private final Condition full = this.lock.newCondition();
- private final Condition empty = this.lock.newCondition();
- private boolean isFull;
- private boolean isEmpty;
- // private boolean isFull() {
- // return null != this.cargoHolder;
- // }
- public StorageImplementation(int cargoHolderSize){
- cargoHolder = new CargoHolder(cargoHolderSize);
- }
- @Override
- public void put(Cargo cargo) throws InterruptedException {
- this.lock.lock();
- try {
- if (isFull)
- this.empty.await();
- while (true) {
- if (!cargoHolder.add(cargo)) {
- isFull = true;
- this.empty.await();
- } else
- System.out.println("Loading!");
- break;
- }
- isEmpty = false;
- this.full.signal();
- }
- /*}catch (InterruptedException e){ throw e;*/ finally {
- this.lock.unlock();
- }
- }
- @Override
- public void moveOldestCargoToOtherStorage(Storage storage) throws InterruptedException {
- this.lock.lock();
- try {
- if (isEmpty)
- this.full.await();
- while (true) {
- Cargo cargo = cargoHolder.removeCargoByIndex(0);
- if (null == cargo) {
- isEmpty = true;
- this.full.await();
- } else {
- storage.put(cargo);
- //if (!storage.put(cargo))
- System.out.println("Moving to storage");
- break;
- }
- }
- isFull = false;
- this.empty.signal();
- }
- /*}catch (InterruptedException e){ throw e;*/ finally {
- this.lock.unlock();
- }
- }
- // public static void main(String[] args) {
- // Storage storage = new StorageImpl();
- // for (int i = 0; i < 100; i++)
- // new Producer(storage).start();
- // for (int i = 0; i < 100; i++)
- // new Consumer(storage).start();
- // }
- public boolean isFull() {
- return isFull;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement