+++ /dev/null
-package pnews.servlet;
-
-import java.lang.ref.WeakReference;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.logging.Logger;
-
-import pnews.Article;
-
-public class ArticleStore {
- public final static ArticleStore singleton = new ArticleStore();
- private final HashMap<String, WeakReference<Article>> articles = new HashMap<>();
- private final static Logger LOG = Logger.getLogger(ArticleStore.class.getName());
-
- public Article get(String link) {
- WeakReference<Article> ref;
- Article result;
-
- synchronized (articles) {
- ref = articles.get(link);
- if (ref == null) {
- return null;
- }
-
- result = ref.get();
- if (result == null) {
- LOG.info("Article has been released from memory: " + link);
- articles.remove(link);
- }
-
- return result;
- }
- }
-
- public Article getArticle(String link, ArticleFactory factory) {
- Article result;
-
- synchronized (articles) {
- result = get(link);
- if (result == null) {
- result = factory.create();
- articles.put(link, new WeakReference<>(result));
- LOG.fine("Article has been added: " + result.link);
- }
-
- return result;
- }
- }
-
- public long size() {
- synchronized (this) {
- return articles.size();
- }
- }
-
- public Article[] getArticles() {
- ArrayList<Article> result;
- Article a;
-
- synchronized (articles) {
- result = new ArrayList<>(articles.size());
-
- for (WeakReference<Article> r: articles.values()) {
- a = r.get();
- if (a != null)
- result.add(a);
- }
-
- return result.toArray(new Article[] {});
- }
- }
-}