ref - JiyangM/spring GitHub Wiki

java.lang.ref 包中定义了四种引用类型和引用队列。

  • FinalReference 强引用,包内可用。强引用可能导致内存溢出,因为强引用对象不会被垃圾收集器回收。

  • SoftReference 软引用,包外可直接使用。jvm会根据内存情况进行回收软引用的对象,适合做缓存。

  • WeakReference 弱引用,包外可直接使用。jvm 垃圾回收线程只要发现弱引用就会回收,由于垃圾收集线程的优先级较低,所以弱引用可能会长期存在。

  • PhantomReference 虚引用,包外可直接使用。通过get获取强引用时,永远获取不到。不知道干嘛用的!

demo

 private static class Page {
        // TODO: prevent the document from being modified
        private Document doc;
        private String content;
        private ContentType contentType;
        private int httpStatus;
        private long lastModified;
        
        public Page(Document doc, String content, ContentType contenType, int httpStatus, long lastModified) {
            this.doc = doc;
            this.content = content;
            this.contentType = contenType;
            this.httpStatus = httpStatus;
            this.lastModified = lastModified;
        }
    }


private volatile transient SoftReference<Page> pageRef;


private Page doGet() throws IOException {
        if (pageRef != null) {
            Page page = pageRef.get();
            if (page != null) {
                return page;
            }
        }

        try (PageReader reader = connectionBuilder().reader()) {
            return setPage(fetchPage(reader));
        }
    }


private Page setPage(Page page) {
        page.doc.setDocumentURI(uri.toString());
        pageRef = new SoftReference<>(page);
        return page;
    }

weakHashMap 是weakReference的一种默认实现。 他可以解决HashMap的内存溢出问题。

当我们需要一种大的hash缓存表时,可以使用weakHashMap 。 详见 weakHashMap

⚠️ **GitHub.com Fallback** ⚠️