Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
*.iml
*.xml
1 change: 1 addition & 0 deletions SoftCache/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
*.idea
100 changes: 100 additions & 0 deletions SoftCache/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

<modelVersion>4.0.0</modelVersion>

<groupId>maven</groupId>
<artifactId>softCache</artifactId>
<packaging>jar</packaging>
<version>1.0</version>

<name>A Camel Route</name>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
</properties>

<dependencyManagement>
<dependencies>
<!-- Camel BOM -->
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-parent</artifactId>
<version>2.18.3</version>
<scope>import</scope>
<type>pom</type>
</dependency>
</dependencies>
</dependencyManagement>

<dependencies>

<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-core</artifactId>
</dependency>

<!-- logging -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
<scope>runtime</scope>
</dependency>

<!-- testing -->
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

<build>
<defaultGoal>install</defaultGoal>

<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.1</version>
<configuration>
<encoding>UTF-8</encoding>
</configuration>
</plugin>

<!-- Allows the example to be run via 'mvn compile exec:java' -->
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.5.0</version>
<configuration>
<mainClass>maven.MainApp</mainClass>
<includePluginDependencies>false</includePluginDependencies>
</configuration>
</plugin>

</plugins>
</build>

</project>
23 changes: 23 additions & 0 deletions SoftCache/src/main/java/maven/Cache.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package maven;

public interface Cache<K, V> {
/**
* Возвращает соответствующее значение, если оно ещё в кэше, иначе null
*/
V getIfPresent(K key);

/**
* Сохраняет value по соответствующему ключу key
*/
void put(K key, V value);

/**
* Удаляет соответствующее ключу key значение
*/
V remove(K key);

/**
* Очищает кэш
*/
void clear();
}
111 changes: 111 additions & 0 deletions SoftCache/src/main/java/maven/SoftCacheMap.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
package maven;

import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;

public class SoftCacheMap<K, V> implements Cache<K, V> {

private HashMap<K, SoftReference<V>> cache;
private HashMap<SoftReference<V>, HashSet<K>> subsidiaryMap;
private ReferenceQueue<V> referenceQueue;
private Deque<V> recentlyUsed;
private int maxSize;
private int cleaningFrequency;
private int numOfPuts;

protected SoftCacheMap(int size, int frequency) {
cache = new HashMap<>();
/**
* второй hashMap - вспомогательный, используется при удалении из кэша
* тех ссылок, которые попали в referenceQueue. Чтобы не искать все ключи,
* соответствующие одной ссылке, храню Set из таких ключей в качестве значения
* во втором hashMap-e.
*/
subsidiaryMap = new HashMap<>();
referenceQueue = new ReferenceQueue<>();
recentlyUsed = new LinkedList<>();
maxSize = size;
cleaningFrequency = frequency;
numOfPuts = 0;
}

private void putInQueue(V object) {
if (maxSize > 0) {
if (object != null) {
recentlyUsed.remove(object);
if (recentlyUsed.size() < maxSize) {
recentlyUsed.addLast(object);
} else {
recentlyUsed.addLast(object);
recentlyUsed.removeFirst();
}
}
}
}


private void clean() {
boolean done = false;
while (!done) {
SoftReference reference = (SoftReference) referenceQueue.poll();
if (reference != null) {
if (subsidiaryMap.containsKey(reference)) {
HashSet<K> localSet = subsidiaryMap.remove(reference);
for (K local : localSet) {
if (reference.get() == null) {
cache.remove(local);
}
}
}
} else {
done = true;
}
}
}

@Override
public V getIfPresent(K key) {
if (cache.containsKey(key)) {
putInQueue(cache.get(key).get());
return cache.get(key).get();
}
return null;
}

@Override
public void put(K key, V value) {
++numOfPuts;
SoftReference<V> reference = new SoftReference<>(value, referenceQueue);
cache.put(key, reference);
putInQueue(value);
if (subsidiaryMap.containsKey(reference)) {
subsidiaryMap.get(reference).add(key);
} else {
subsidiaryMap.put(reference, new HashSet<>());
subsidiaryMap.get(reference).add(key);
}
if (numOfPuts % cleaningFrequency == 0) {
clean();
}
}

@Override
public V remove(K key) {
if ((cache.containsKey(key)) && (cache.get(key).get() != null)) {
subsidiaryMap.remove(cache.get(key));
return cache.remove(key).get();
}
return null;
}

@Override
public void clear() {
cache.clear();
subsidiaryMap.clear();
}

}
7 changes: 7 additions & 0 deletions SoftCache/src/main/resources/log4j2.properties
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@

appender.out.type = Console
appender.out.name = out
appender.out.layout.type = PatternLayout
appender.out.layout.pattern = [%30.30t] %-30.30c{1} %-5p %m%n
rootLogger.level = INFO
rootLogger.appenderRef.out.ref = out
93 changes: 93 additions & 0 deletions SoftCache/src/test/java/maven/SoftCacheMapTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
package maven;

import org.junit.Assert;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;

public class SoftCacheMapTest {

private SoftCacheMap<Integer, Integer> getCache(int size, int frequency) {
return new SoftCacheMap<>(size, frequency);
}

private void testBefore(int size, int frequency, ArrayList<Integer> values,
ArrayList<Integer> expectedBefore) throws Exception {

String errorMessage = "Bad result";
SoftCacheMap<Integer, Integer> cache = getCache(size, frequency);
for (int i = 0; i < values.size(); ++i) {
cache.put(i, values.get(i));
}
for (int i = 0; i < values.size(); ++i) {
Assert.assertEquals(errorMessage, expectedBefore.get(i), cache.getIfPresent(i));
}
}

private void testAfter(int size, int frequency, ArrayList<Integer> values,
ArrayList<Integer> expectedAfter) {
String errorMessage = "Bad result";
SoftCacheMap<Integer, Integer> cache = getCache(size, frequency);
for (int i = 0; i < values.size(); ++i) {
cache.put(i, new Integer(values.get(i)));
}
try {
Object[] big = new Object[(int) Runtime.getRuntime().maxMemory()];
} catch (OutOfMemoryError e) {
// ignore
}

int counter = 0;
for (int i = 0; i < values.size(); ++i) {
if (cache.getIfPresent(i) != null) {
Assert.assertEquals(errorMessage, expectedAfter.get(counter), cache.getIfPresent(i));
++counter;
}
}
}

@Test
public void testReferenceQueueBefore() throws Exception {
ArrayList<Integer> values = new ArrayList<>(Arrays.asList(0, 1, 2, 3, 4, 5));
ArrayList<Integer> expectedBefore = new ArrayList<>(Arrays.asList(0, 1, 2, 3, 4, 5));
testBefore(0, 1, values, expectedBefore);
}

@Test
public void testReferenceQueueAfter() throws Exception {
ArrayList<Integer> values = new ArrayList<>(Arrays.asList(0, 1, 2, 3, 4, 5));
testAfter(0, 1, values, null);
}

@Test
public void testRecentlyUsedQueueAfter0() throws Exception {
ArrayList<Integer> values = new ArrayList<>(Arrays.asList(0, 1, 2, 3, 4, 5));
ArrayList<Integer> expectedAfter = new ArrayList<>(Arrays.asList(4, 5));
testAfter(2, 1, values, expectedAfter);
}

@Test
public void testRecentlyUsedQueueAfter1() throws Exception {
ArrayList<Integer> values = new ArrayList<>(Arrays.asList(0, 1, 2, 3, 4, 5));
ArrayList<Integer> expectedAfter = new ArrayList<>(Arrays.asList(2, 5));
String errorMessage = "Bad result";
SoftCacheMap<Integer, Integer> cache = getCache(2, 1);
for (int i = 0; i < values.size(); ++i) {
cache.put(i, new Integer(values.get(i)));
}
cache.getIfPresent(2);
try {
Object[] big = new Object[(int) Runtime.getRuntime().maxMemory()];
} catch (OutOfMemoryError e) {
// ignore
}

int counter = 0;
for (int i = 0; i < values.size(); ++i) {
if (cache.getIfPresent(i) != null) {
Assert.assertEquals(errorMessage, expectedAfter.get(counter), cache.getIfPresent(i));
++counter;
}
}
}
}