76 lines
1.9 KiB
Java
76 lines
1.9 KiB
Java
package exercises.ex_n_bis;
|
|
|
|
import java.util.ArrayList;
|
|
import java.util.HashMap;
|
|
import java.util.Map;
|
|
import java.util.concurrent.locks.Lock;
|
|
import java.util.concurrent.locks.ReentrantReadWriteLock;
|
|
|
|
public class LibraryCatalog {
|
|
private final Map<String, String> catalog = new HashMap<>();
|
|
private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
|
|
private final Lock readLock = lock.readLock();
|
|
private final Lock writeLock = lock.writeLock();
|
|
|
|
public LibraryCatalog() {
|
|
|
|
}
|
|
|
|
public ArrayList<Book> getBooks() {
|
|
ArrayList<Book> books = new ArrayList<>();
|
|
try {
|
|
readLock.lock();
|
|
catalog.forEach((title, author) -> {
|
|
books.add(new Book(title, author));
|
|
});
|
|
} finally {
|
|
readLock.unlock();
|
|
}
|
|
return books;
|
|
}
|
|
|
|
public String findBook(String title) {
|
|
String author;
|
|
try {
|
|
readLock.lock();
|
|
author = catalog.get(title);
|
|
} finally {
|
|
readLock.unlock();
|
|
}
|
|
if (author == null) {
|
|
System.out.println("The book '" + title + "' is not in the catalog");
|
|
return null;
|
|
}
|
|
return author;
|
|
}
|
|
|
|
public void addBook(String title, String author) {
|
|
try {
|
|
writeLock.lock();
|
|
catalog.put(title, author);
|
|
} finally {
|
|
writeLock.unlock();
|
|
}
|
|
}
|
|
|
|
public void removeBook(String title) {
|
|
try {
|
|
writeLock.lock();
|
|
catalog.remove(title);
|
|
} finally {
|
|
writeLock.unlock();
|
|
}
|
|
}
|
|
|
|
public void updateBook(String title, String newAuthor) {
|
|
try {
|
|
writeLock.lock();
|
|
catalog.replace(title, newAuthor);
|
|
} finally {
|
|
writeLock.unlock();
|
|
}
|
|
}
|
|
|
|
public record Book(String title, String author) {}
|
|
}
|