Friday, 24 July 2015

Blocking queue using 'synchronized' block

public class MyBlockingQueue_Sync {
private Queue items = new LinkedList<>();
private Object lock = new Object();
public void put(String item) {
synchronized(lock) {
System.out.println("Writing");
this.items.add(item);
this.lock.notify();
System.out.println("Written");
}
}
public String get() {
synchronized(lock) {
System.out.println("Reading");
if(this.items.size() == 0) {
this.waitforput();
}
String item = this.items.poll();
System.out.println("Read");
return item;
}
}
void waitforput() {
try {
this.lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}

}

My Blocking Queue using Lock interface

import java.util.*;
import java.util.concurrent.locks.*;

public class MyBlockingQueue {
private Queue items = new LinkedList<>();
private Lock lock = new ReentrantLock();
public void put(String item) {
try {
this.lock.lock();
System.out.println("Writing");
this.items.add(item);
}
finally {
this.lock.unlock();
System.out.println("Written");
}
}
public String get() {
try {
System.out.println("Reading");
this.tryLock();
return this.items.poll();
}
finally {
this.lock.unlock();
System.out.println("Read");
}
}
void tryLock() {
while(true) {
this.lock.lock();
if(this.items.size() == 0) {
this.lock.unlock();
sleep();
} else {
return;
}
}
}

private void sleep() {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
System.out.println("Interrupted");
}
}

}