Skip to content

Commit

Permalink
Resolves #892: Restrict the ComparableVersion cache size
Browse files Browse the repository at this point in the history
  • Loading branch information
jarmoniuk authored and slawekjaranowski committed Jan 2, 2023
1 parent 2a755ad commit c8a29db
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 4 deletions.
5 changes: 5 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -237,6 +237,11 @@
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.4</version>
</dependency>
<dependency>
<groupId>org.apache.maven.plugin-testing</groupId>
<artifactId>maven-plugin-testing-harness</artifactId>
Expand Down
5 changes: 4 additions & 1 deletion versions-common/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,10 @@
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>

<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
</dependency>
<dependency>
<groupId>org.apache.maven.plugin-testing</groupId>
<artifactId>maven-plugin-testing-harness</artifactId>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,9 @@
import java.util.Map;
import java.util.Properties;
import java.util.Stack;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantReadWriteLock;

import org.apache.commons.collections4.map.LRUMap;

/**
* Generic implementation of version comparison.
Expand All @@ -39,7 +41,9 @@
* Note: The implementation of the maven core should be used.
*/
public class ComparableVersion implements Comparable<ComparableVersion> {
private static final Map<String, ComparableVersion> CACHE = new ConcurrentHashMap<>();
private static final int MAX_CACHE_SIZE = 0x200;
private static final Map<String, ComparableVersion> CACHE = new LRUMap<>(MAX_CACHE_SIZE);
private static final ReentrantReadWriteLock CACHE_LOCK = new ReentrantReadWriteLock();

private String value;

Expand Down Expand Up @@ -291,7 +295,21 @@ public String toString() {
* Get a ComparableVersion representing the version in a string.
*/
public static ComparableVersion of(String version) {
return CACHE.computeIfAbsent(version, ComparableVersion::new);
try {
CACHE_LOCK.readLock().lock();
ComparableVersion result = CACHE.get(version);
if (result != null) {
return result;
}
} finally {
CACHE_LOCK.readLock().unlock();
}
try {
CACHE_LOCK.writeLock().lock();
return CACHE.computeIfAbsent(version, ComparableVersion::new);
} finally {
CACHE_LOCK.writeLock().unlock();
}
}

/**
Expand Down

0 comments on commit c8a29db

Please sign in to comment.