#10 effective java: item 7

This commit is contained in:
haerong22
2022-05-25 02:11:12 +09:00
parent 8188d0fc15
commit fe6feed168
9 changed files with 287 additions and 0 deletions

View File

@@ -0,0 +1,59 @@
package com.example.effectivejava.chapter01.item07.cache;
import org.junit.jupiter.api.Test;
import java.util.*;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import static org.junit.jupiter.api.Assertions.*;
class PostRepositoryTest {
@Test
void cache() throws InterruptedException {
PostRepository postRepository = new PostRepository();
CacheKey key1 = new CacheKey(1);
postRepository.getPostById(key1);
assertFalse(postRepository.getCache().isEmpty());
key1 = null;
// TODO run gc
System.out.println("run gc");
System.gc();
System.out.println("wait");
Thread.sleep(3000L);
assertTrue(postRepository.getCache().isEmpty());
}
@Test
void backgroundThread() throws InterruptedException {
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
PostRepository postRepository = new PostRepository();
CacheKey key1 = new CacheKey(1);
postRepository.getPostById(key1);
Runnable removeOldCache = () -> {
System.out.println("running removeOldCache task");
Map<CacheKey, Post> cache = postRepository.getCache();
Set<CacheKey> cacheKeys = cache.keySet();
Optional<CacheKey> key = cacheKeys.stream().min(Comparator.comparing(CacheKey::getCreated));
key.ifPresent((k) -> {
System.out.println("removing " + k);
cache.remove(k);
});
};
System.out.println("The time is : " + new Date());
executor.scheduleAtFixedRate(removeOldCache,
1, 3, TimeUnit.SECONDS);
Thread.sleep(20000L);
executor.shutdown();
}
}

View File

@@ -0,0 +1,32 @@
package com.example.effectivejava.chapter01.item07.listener;
import org.junit.jupiter.api.Test;
import java.lang.ref.WeakReference;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
class ChatRoomTest {
@Test
void charRoom() throws InterruptedException {
ChatRoom chatRoom = new ChatRoom();
User user1 = new User();
User user2 = new User();
chatRoom.addUser(user1);
chatRoom.addUser(user2);
chatRoom.sendMessage("hello");
user1 = null;
System.gc();
Thread.sleep(5000L);
List<WeakReference<User>> users = chatRoom.getUsers();
assertEquals(1, users.size());
}
}