0

I'm trying to implement a image caching system that would pause after it inserts 5 images into the cache.

public void run() {
    int index = 0;
    lock.lock();
    try {
        while (index < list.getJpegCount() && !bCancel) {
            String file = list.getJpeg(index);
            images.put(file,
                    ImageUtils.getThumbNail(list.getJpeg(index), size));
            index++;
            batchCount++;
            Console.writeLine("Object cached: " + file);
            if (batchCount > 5) {
                try {
                    batchCount = 0;
                    Console.writeLine("Waiting for next batch...");
                    bufferEmpty.await();
                    Console.writeLine("We are back...");
                } catch (InterruptedException ex) {
                    Logger.getLogger(JpegCache.class.getName()).log(
                            Level.SEVERE, null, ex);
                }
            }
        }
    } finally {
        lock.unlock();
    }
}

now the problems is that I want to wake up the thread using the following, but it doesn't wake up:

public Image getNext()
{        
    lock.lock();
    currentIndex++;
    String filename=list.getJpeg(currentIndex);

    if (!images.containsKey(filename))
    {
        bufferEmpty.signalAll();            
        Console.writeLine("Start next batch...");
        return ImageUtils.getThumbNail(filename, size);           

    }else
        return images.get(filename);

}

What's wrong?

Pshemo
  • 122,468
  • 25
  • 185
  • 269
Arash N
  • 324
  • 1
  • 2
  • 10
  • How are you obtaining the `bufferEmpty` condition? – Jon Lin Jul 20 '12 at 21:43
  • Like this: final Lock lock = new ReentrantLock(); final Condition bufferEmpty = lock.newCondition(); – Arash N Jul 20 '12 at 22:18
  • I posted a mechanism for [pausing a thread](http://stackoverflow.com/questions/10665780/more-efficient-way-for-pausing-loop-wanted/10669623#10669623) here recently. It may be of interest. – OldCurmudgeon Jul 20 '12 at 22:43
  • Your code was too complicated. there should be an easier way to wake up the thread using monitors. – Arash N Jul 20 '12 at 23:11

1 Answers1

0

SOLUTION:

I forgot to unlock the lock:

public Image getNext()
{        
    lock.lock();
    currentIndex++; 
    String filename=list.getJpeg(currentIndex);
    if (!images.containsKey(filename))
    {
        bufferEmpty.signalAll();
        lock.unlock();
        Console.writeLine("Start next batch...");
        return ImageUtils.getThumbNail(filename, size);           

    }else
    {
        lock.unlock();
        return images.get(filename);
    }
}
Arash N
  • 324
  • 1
  • 2
  • 10