CS 151 - Lecture 25

Cay S. Horstmann
Puzzler: What is Wrong?
public class BoundedQueue<E>
{
private Object queueLock = "LOCK";
. . .
public void add(E newValue) throws InterruptedException
{
synchronized (queueLock)
{
while (size == elements.length)
spaceAvailableCondition.wait();
elements[tail] = newValue;
tail++;
size++;
if (tail == elements.length)
tail = 0;
valueAvailableCondition.signalAll();
}
}
}
Puzzler: What is Wrong?
public class BoundedQueue<E>
{
. . .
public void add(E newValue) throws InterruptedException
{
synchronized (new String("LOCK"))
{
while (size == elements.length)
spaceAvailableCondition.wait();
elements[tail] = newValue;
tail++;
size++;
if (tail == elements.length)
tail = 0;
valueAvailableCondition.signalAll();
}
}
}
Puzzler: What is Wrong?
public class BoundedQueue<E>
{
private Lock queueLock = new ReentrantLock();
private Condition valueAvailableCondition
= queueLock.newCondition();
. . .
public void add(E newValue) throws InterruptedException
{
queueLock.lock();
try
{
while (size == elements.length)
spaceAvailableCondition.wait();
elements[tail] = newValue;
tail++;
size++;
if (tail == elements.length)
tail = 0;
valueAvailableCondition.signalAll();
}
finally
{
queueLock.unlock();
}
}
}
Puzzler: What is Wrong?
public class BoundedQueue<E>
{
. . .
public void write(String filename) throws IOException
{
queueLock.lock();
try
{
PrintWriter out = new PrintWriter(filename);
int i = head;
for (int j = 0; j < size; j++)
{
out.println(elements[i]);
i = (i + 1) % elements.length;
}
}
finally
{
out.close();
queueLock.unlock();
}
}
}