|
| 1 | +package com.sun.jvm.Jvm; |
| 2 | + |
| 3 | +import java.lang.ref.ReferenceQueue; |
| 4 | +import java.lang.ref.SoftReference; |
| 5 | + |
| 6 | +/** |
| 7 | + * @ClassName SoftReFQ |
| 8 | + * @Despacito TODO |
| 9 | + * @Author chenzhuo |
| 10 | + * @Version 1.0 |
| 11 | + * -Xmx10M -XX:+PrintGC |
| 12 | + * 没有回收引用 |
| 13 | + * |
| 14 | + **/ |
| 15 | +public class SoftReFQ { |
| 16 | + public static class User { |
| 17 | + private int id; |
| 18 | + private String name; |
| 19 | + public User(int id, String name) { |
| 20 | + this.id = id; |
| 21 | + this.name = name; |
| 22 | + } |
| 23 | + |
| 24 | + @Override |
| 25 | + public String toString() { |
| 26 | + return "User{" + |
| 27 | + "id=" + id + |
| 28 | + ", name='" + name + '\'' + |
| 29 | + '}'; |
| 30 | + } |
| 31 | + } |
| 32 | + |
| 33 | + static ReferenceQueue<User> queue = null; |
| 34 | + |
| 35 | + public static class CheckReQueue extends Thread { |
| 36 | + public void run() { |
| 37 | + while (true) { |
| 38 | + if (queue != null) { |
| 39 | + UserSoftRereence userSoftRereence = null; |
| 40 | + try { |
| 41 | + /* System.out.println("userReferenceQueue:"+ |
| 42 | + userSoftRereence.get());*/ |
| 43 | + userSoftRereence = (UserSoftRereence) queue.remove(); |
| 44 | + } catch (InterruptedException e) { |
| 45 | + e.printStackTrace(); |
| 46 | + } |
| 47 | + if (userSoftRereence != null) { |
| 48 | + System.out.println("user id" + |
| 49 | + userSoftRereence.userId + " is delete"); |
| 50 | + } |
| 51 | + } |
| 52 | + } |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | + /** |
| 57 | + * 强引用 不会回收 |
| 58 | + * 软引用 比强引用弱一点,内存不足的时候就会被回收 |
| 59 | + * 弱信用 回收,gc的时候发现就会回收 |
| 60 | + * 虚引用 最弱 |
| 61 | + */ |
| 62 | + public static class UserSoftRereence extends SoftReference<User> { |
| 63 | + int userId; |
| 64 | + |
| 65 | + public UserSoftRereence(User referent, ReferenceQueue<? super User> queue) { |
| 66 | + super(referent); |
| 67 | + userId = referent.id; |
| 68 | + } |
| 69 | + } |
| 70 | + |
| 71 | + public static void main(String[] args) throws InterruptedException { |
| 72 | + Thread thread = new CheckReQueue(); |
| 73 | + thread.setDaemon(true); |
| 74 | + thread.start(); |
| 75 | + User user = new User(1,"chenzhuo"); |
| 76 | + queue = new ReferenceQueue<>(); |
| 77 | + UserSoftRereence userSoftRereence |
| 78 | + = new UserSoftRereence(user,queue); |
| 79 | + user = null; |
| 80 | + System.out.println(userSoftRereence.get()); |
| 81 | + System.gc(); |
| 82 | + System.out.println("After GC:"); |
| 83 | + System.out.println(userSoftRereence.get()); |
| 84 | + System.out.println("尝试创建字节 和回收"); |
| 85 | + byte[] b = new byte[7*1024*925]; |
| 86 | + System.gc(); |
| 87 | + System.out.println(userSoftRereence.get()); |
| 88 | + Thread.sleep(1000); |
| 89 | + } |
| 90 | + |
| 91 | +} |
0 commit comments