0

I'm trying to implement at playlist in java. The only problem is that populatePlaylist() is a bit slow and needs to be locked. I have written this code but it doesn't seem to work.

        private static final Lock lock = new ReentrantLock();

        public Playlist(Context context, int length, boolean isLocked) {
                lock.lock();
                this.mContext = context;
                this.populatePlaylist(length);

                // If the playlist is locked we do not unlock it.
                // wait for someone to do it manually.
                if (!isLocked)
                        lock.unlock();
        }

        public void unlock() {
                lock.unlock();
        }

When the constructor is called the second time it just executes all the code even though unlock() has never been called.

EDIT: Here is what I try to do. The playlist class is just a representation of a playlist (surprise :) ). populate playlist may be a bit slow to generate so I share the playlist class between different parts of the program in order to avoid loading the playlist more than once. Yes, the playlist is only created once in every thread. One the UI mode, once it a background thread, once other places as well.

The playlist is static. Inside "populateplaylist" the code looks somewhat like this:

if (playlist.isEmpty()) { create_playlist } else {nothing}
Markus
  • 2,526
  • 4
  • 28
  • 35
  • 3
    This is not how to use a lock. And why do you lock in the constructor? It does not make any sense – fge Jul 20 '13 at 14:15
  • 1
    Please tell what you want to achieve with this playlist. It looks like an XY problem. – fge Jul 20 '13 at 14:18
  • 1
    The constructor is called the second time on the same thread, right? A ReentrantLock allows the same thread to call lock() multiple times without blocking; that's the whole point of it. (But don't change to a non-reentrant lock, you'll just get a deadlock instead.) You need to clarify what you're actually trying to achieve. – Alan Stokes Jul 20 '13 at 14:20
  • @fge I explained a bit more in the original question. I have to admit I'm not sure I'm solving the problem the correct way. – Markus Jul 20 '13 at 14:26
  • OK, what are the `context` and `length` arguments in your current constructor? – fge Jul 20 '13 at 16:10
  • @fge Not terrible relevant. context is an Android class and length is just the length of the playlist (removed from the example) – Markus Jul 20 '13 at 21:51
  • Both are, on the opposite, quite relevant. For instance, when you run your app, can there be more than one context? More than one length? – fge Jul 20 '13 at 22:28

0 Answers0