package reentrantrwlock; import java.util.Map; import java.util.List; import java.util.Random; import java.util.TreeMap; import java.util.ArrayList; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.Iterator; public class MovieCatalog { private final Map movies; private final ReentrantReadWriteLock rwlock; private final Lock rLock, wLock; private static final Random generator = new Random(); public MovieCatalog() { movies = new TreeMap<>(); rwlock = new ReentrantReadWriteLock(); rLock = rwlock.readLock(); wLock = rwlock.writeLock(); } /** * Returns the current size of this catalog * @return the size of this catalog */ public int getSize() { int length; rLock.lock(); length = movies.size(); rLock.unlock(); return length; } /** * Returns a movie from this catalog * @param the title of movie to be obtained * @return the movie with the title provided or * null if the movie is not in the catalog */ public Movie getMovie(String title) { Movie m; rLock.lock(); m = movies.get(title); rLock.unlock(); return m; } /** * Returns the list of all movie titles in this catalog * @return a list of the movie titles in this catalog */ public List getTitles() { List titles; rLock.lock(); titles = new ArrayList<>(movies.keySet()); rLock.unlock(); return titles; } /** * Returns a random movie from this catalog * @return a randomly selected movie from this catalog */ public Movie getRandomMovie() { Movie m; rLock.lock(); final int r = generator.nextInt(movies.size()) - 1; final Iterator it = movies.values().iterator(); for (int i = 0; i < r; i++) { it.next(); } m = it.next(); rLock.unlock(); return m; } /** * Adds a movie to the catalog * @param the movie to be added to the catalog */ public void addMovie(Movie movie) { wLock.lock(); movies.put(movie.getTitle(), movie); wLock.unlock(); } }