diff --git a/README.md b/README.md index bba54a2b..9b0e50ca 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ java-util Rare, hard-to-find utilities that are thoroughly tested (> 98% code coverage via JUnit tests). Available on [Maven Central](http://search.maven.org/#search%7Cga%7C1%7Cjava-util). This library has no dependencies on other libraries for runtime. -The`.jar`file is only`148K.` +The`.jar`file is only`152K.` Works with`JDK 1.8`through`JDK 21`. The classes in the`.jar`file are version 52 (`JDK 1.8`). @@ -15,7 +15,7 @@ The classes in the`.jar`file are version 52 (`JDK 1.8`). To include in your project: ##### Gradle ``` -implementation 'com.cedarsoftware:java-util:2.3.0' +implementation 'com.cedarsoftware:java-util:2.4.0' ``` ##### Maven @@ -23,7 +23,7 @@ implementation 'com.cedarsoftware:java-util:2.3.0' com.cedarsoftware java-util - 2.3.0 + 2.4.0 ``` --- @@ -47,6 +47,9 @@ String s = convertToString(atomicLong) Included in java-util: * **ArrayUtilities** - Useful utilities for working with Java's arrays `[]` * **ByteUtilities** - Useful routines for converting `byte[]` to HEX character `[]` and visa-versa. +* **ClassUtilities** - Useful utilities for Class work. For example, call `computeInheritanceDistance(source, destination)` to get the inheritance distance (number of super class steps to make it from source to destination. It will return the distance as an integer. If there is no inheritance relationship between the two, +then -1 is returned. The primitives and primitive wrappers return 0 distance as if they are the +same class. * **Sets** * **CompactSet** - Small memory footprint `Set` that expands to a `HashSet` when `size() > compactSize()`. * **CompactLinkedSet** - Small memory footprint `Set` that expands to a `LinkedHashSet` when `size() > compactSize()`. @@ -59,6 +62,7 @@ Included in java-util: * **CompactCILinkedMap** - Small memory footprint `Map` that expands to a case-insensitive `LinkedHashMap` when `size() > compactSize()` entries. * **CompactCIHashMap** - Small memory footprint `Map` that expands to a case-insensitive `HashMap` when `size() > compactSize()` entries. * **CaseInsensitiveMap** - `Map` that ignores case when `Strings` are used as keys. + * **LRUCache** - Thread safe LRUCache that implements the full Map API and supports a maximum capacity. Once max capacity is reached, placing another item in the cache will cause the eviction of the item that was the least recently used (LRU). * **TrackingMap** - `Map` class that tracks when the keys are accessed via `.get()` or `.containsKey()`. Provided by @seankellner * **Converter** - Convert from one instance to another. For example, `convert("45.3", BigDecimal.class)` will convert the `String` to a `BigDecimal`. Works for all primitives, primitive wrappers, `Date`, `java.sql.Date`, `String`, `BigDecimal`, `BigInteger`, `AtomicBoolean`, `AtomicLong`, etc. The method is very generous on what it allows to be converted. For example, a `Calendar` instance can be input for a `Date` or `Long`. Examine source to see all possibilities. * **DateUtilities** - Robust date String parser that handles date/time, date, time, time/date, string name months or numeric months, skips comma, etc. English month names only (plus common month name abbreviations), time with/without seconds or milliseconds, `y/m/d` and `m/d/y` ordering as well. diff --git a/changelog.md b/changelog.md index ef6288ba..9d234537 100644 --- a/changelog.md +++ b/changelog.md @@ -1,4 +1,7 @@ ### Revision History +* 2.4.0 + * Added ClassUtilities. This class has a method to get the distance between a source and destination class. It includes support for Classes, multiple inheritance of interfaces, primitives, and class-to-interface, interface-interface, and class to class. + * Added LRUCache. This class provides a simple cache API that will evict the least recently used items, once a threshold is met. * 2.3.0 * Added `FastReader` and `FastWriter.` * `FastReader` can be used instead of the JDK `PushbackReader(BufferedReader)).` It is much faster with no synchronization and combines both. It also tracks line `[getLine()]`and column `[getCol()]` position monitoring for `0x0a` which it can be queried for. It also can be queried for the last snippet read: `getLastSnippet().` Great for showing parsing error messages that accurately point out where a syntax error occurred. Make sure you use a new instance per each thread. diff --git a/pom.xml b/pom.xml index 2b0a27ed..501a28d9 100644 --- a/pom.xml +++ b/pom.xml @@ -5,7 +5,7 @@ com.cedarsoftware java-util jar - 2.3.0 + 2.4.0 Java Utilities https://github.com/jdereg/java-util diff --git a/src/main/java/com/cedarsoftware/util/ClassUtilities.java b/src/main/java/com/cedarsoftware/util/ClassUtilities.java new file mode 100644 index 00000000..0501de43 --- /dev/null +++ b/src/main/java/com/cedarsoftware/util/ClassUtilities.java @@ -0,0 +1,145 @@ +package com.cedarsoftware.util; + +import java.util.HashSet; +import java.util.LinkedList; +import java.util.Queue; +import java.util.Set; + +/** + * Useful utilities for Class work. For example, call computeInheritanceDistance(source, destination) + * to get the inheritance distance (number of super class steps to make it from source to destination. + * It will return the distance as an integer. If there is no inheritance relationship between the two, + * then -1 is returned. The primitives and primitive wrappers return 0 distance as if they are the + * same class. + *

+ * @author John DeRegnaucourt (jdereg@gmail.com) + *
+ * Copyright (c) Cedar Software LLC + *

+ * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +public class ClassUtilities +{ + private static final Set> prims = new HashSet<>(); + static + { + prims.add(Byte.class); + prims.add(Short.class); + prims.add(Integer.class); + prims.add(Long.class); + prims.add(Float.class); + prims.add(Double.class); + prims.add(Character.class); + prims.add(Boolean.class); + } + + /** + * Computes the inheritance distance between two classes/interfaces/primitive types. + * @param source The source class, interface, or primitive type. + * @param destination The destination class, interface, or primitive type. + * @return The number of steps from the source to the destination, or -1 if no path exists. + */ + public static int computeInheritanceDistance(Class source, Class destination) { + if (source == null || destination == null) { + return -1; + } + if (source.equals(destination)) { + return 0; + } + + // Check for primitive types + if (source.isPrimitive()) { + if (destination.isPrimitive()) { + // Not equal because source.equals(destination) already chceked. + return -1; + } + if (!isPrimitive(destination)) { + return -1; + } + return comparePrimitiveToWrapper(destination, source); + } + + if (destination.isPrimitive()) { + if (!isPrimitive(source)) { + return -1; + } + return comparePrimitiveToWrapper(source, destination); + } + + Queue> queue = new LinkedList<>(); + Set> visited = new HashSet<>(); + queue.add(source); + visited.add(source); + + int distance = 0; + + while (!queue.isEmpty()) { + int levelSize = queue.size(); + distance++; + + for (int i = 0; i < levelSize; i++) { + Class current = queue.poll(); + + // Check superclass + if (current.getSuperclass() != null) { + if (current.getSuperclass().equals(destination)) { + return distance; + } + if (!visited.contains(current.getSuperclass())) { + queue.add(current.getSuperclass()); + visited.add(current.getSuperclass()); + } + } + + // Check interfaces + for (Class interfaceClass : current.getInterfaces()) { + if (interfaceClass.equals(destination)) { + return distance; + } + if (!visited.contains(interfaceClass)) { + queue.add(interfaceClass); + visited.add(interfaceClass); + } + } + } + } + + return -1; // No path found + } + + /** + * @param c Class to test + * @return boolean true if the passed in class is a Java primitive, false otherwise. The Wrapper classes + * Integer, Long, Boolean, etc. are considered primitives by this method. + */ + public static boolean isPrimitive(Class c) + { + return c.isPrimitive() || prims.contains(c); + } + + /** + * Compare two primitives. + * @return 0 if they are the same, -1 if not. Primitive wrapper classes are consider the same as primitive classes. + */ + public static int comparePrimitiveToWrapper(Class source, Class destination) + { + try + { + return source.getField("TYPE").get(null).equals(destination) ? 0 : -1; + } + catch (Exception e) + { + throw new RuntimeException("Error while attempting comparison of primitive types: " + source.getName() + " vs " + destination.getName(), e); + } + } +} diff --git a/src/main/java/com/cedarsoftware/util/FastReader.java b/src/main/java/com/cedarsoftware/util/FastReader.java index e0787e6c..82e583b5 100644 --- a/src/main/java/com/cedarsoftware/util/FastReader.java +++ b/src/main/java/com/cedarsoftware/util/FastReader.java @@ -3,6 +3,27 @@ import java.io.IOException; import java.io.Reader; +/** + * Buffered, Pushback, Reader that does not use synchronization. Much faster than the JDK variants because + * they use synchronization. Typically, this class is used with a separate instance per thread, so + * synchronization is not needed. + *

+ * @author John DeRegnaucourt (jdereg@gmail.com) + *
+ * Copyright (c) Cedar Software LLC + *

+ * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ public class FastReader extends Reader { private Reader in; private char[] buf; diff --git a/src/main/java/com/cedarsoftware/util/FastWriter.java b/src/main/java/com/cedarsoftware/util/FastWriter.java index 7a8049e2..20e326f3 100644 --- a/src/main/java/com/cedarsoftware/util/FastWriter.java +++ b/src/main/java/com/cedarsoftware/util/FastWriter.java @@ -3,6 +3,27 @@ import java.io.IOException; import java.io.Writer; +/** + * Buffered Writer that does not use synchronization. Much faster than the JDK variants because + * they use synchronization. Typically, this class is used with a separate instance per thread, so + * synchronization is not needed. + *

+ * @author John DeRegnaucourt (jdereg@gmail.com) + *
+ * Copyright (c) Cedar Software LLC + *

+ * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ public class FastWriter extends Writer { private static final int DEFAULT_BUFFER_SIZE = 8192; diff --git a/src/main/java/com/cedarsoftware/util/LRUCache.java b/src/main/java/com/cedarsoftware/util/LRUCache.java new file mode 100644 index 00000000..1464a650 --- /dev/null +++ b/src/main/java/com/cedarsoftware/util/LRUCache.java @@ -0,0 +1,165 @@ +package com.cedarsoftware.util; + +import java.util.Collection; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.locks.ReadWriteLock; +import java.util.concurrent.locks.ReentrantReadWriteLock; + +/** + * This class provides a Least Recently Used (LRU) cache API that will evict the least recently used items, + * once a threshold is met. It implements the Map interface for convenience. + *

+ * @author John DeRegnaucourt (jdereg@gmail.com) + *
+ * Copyright (c) Cedar Software LLC + *

+ * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +public class LRUCache implements Map { + private final Map cache; + private final ReadWriteLock lock = new ReentrantReadWriteLock(); + + public LRUCache(int capacity) { + this.cache = Collections.synchronizedMap(new LinkedHashMap(capacity, 0.75f, true) { + protected boolean removeEldestEntry(Map.Entry eldest) { + return size() > capacity; + } + }); + } + + // Implement Map interface + public int size() { + lock.readLock().lock(); + try { + return cache.size(); + } finally { + lock.readLock().unlock(); + } + } + + public boolean isEmpty() { + lock.readLock().lock(); + try { + return cache.isEmpty(); + } finally { + lock.readLock().unlock(); + } + } + + public boolean containsKey(Object key) { + lock.readLock().lock(); + try { + return cache.containsKey(key); + } finally { + lock.readLock().unlock(); + } + } + + public boolean containsValue(Object value) { + lock.readLock().lock(); + try { + return cache.containsValue(value); + } finally { + lock.readLock().unlock(); + } + } + + public V get(Object key) { + lock.readLock().lock(); + try { + return cache.get(key); + } finally { + lock.readLock().unlock(); + } + } + + public V put(K key, V value) { + lock.writeLock().lock(); + try { + return cache.put(key, value); + } finally { + lock.writeLock().unlock(); + } + } + + public V remove(Object key) { + lock.writeLock().lock(); + try { + return cache.remove(key); + } finally { + lock.writeLock().unlock(); + } + } + + public void putAll(Map m) { + lock.writeLock().lock(); + try { + cache.putAll(m); + } finally { + lock.writeLock().unlock(); + } + } + + public void clear() { + lock.writeLock().lock(); + try { + cache.clear(); + } finally { + lock.writeLock().unlock(); + } + } + + public Set keySet() { + lock.readLock().lock(); + try { + return cache.keySet(); + } finally { + lock.readLock().unlock(); + } + } + + public Collection values() { + lock.readLock().lock(); + try { + return cache.values(); + } finally { + lock.readLock().unlock(); + } + } + + public Set> entrySet() { + lock.readLock().lock(); + try { + return cache.entrySet(); + } finally { + lock.readLock().unlock(); + } + } + + public V putIfAbsent(K key, V value) { + lock.writeLock().lock(); + try { + V existingValue = cache.get(key); + if (existingValue == null) { + cache.put(key, value); + return null; + } + return existingValue; + } finally { + lock.writeLock().unlock(); + } + } +} diff --git a/src/main/java/com/cedarsoftware/util/TestUtil.java b/src/main/java/com/cedarsoftware/util/TestUtil.java index e1fce639..5fcb19fe 100644 --- a/src/main/java/com/cedarsoftware/util/TestUtil.java +++ b/src/main/java/com/cedarsoftware/util/TestUtil.java @@ -1,5 +1,10 @@ package com.cedarsoftware.util; +import java.net.URL; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; + /** * Useful Test utilities for common tasks * @@ -76,4 +81,17 @@ public static boolean checkContainsIgnoreCase(String source, String... contains) return true; } + public static String fetchResource(String name) + { + try + { + URL url = TestUtil.class.getResource("/" + name); + Path resPath = Paths.get(url.toURI()); + return new String(Files.readAllBytes(resPath)); + } + catch (Exception e) + { + throw new RuntimeException(e); + } + } } diff --git a/src/test/java/com/cedarsoftware/util/LRUCacheTest.java b/src/test/java/com/cedarsoftware/util/LRUCacheTest.java new file mode 100644 index 00000000..fd4c4961 --- /dev/null +++ b/src/test/java/com/cedarsoftware/util/LRUCacheTest.java @@ -0,0 +1,166 @@ +package com.cedarsoftware.util; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class LRUCacheTest { + + private LRUCache lruCache; + + @BeforeEach + void setUp() { + lruCache = new LRUCache<>(3); + } + + @Test + void testPutAndGet() { + lruCache.put(1, "A"); + lruCache.put(2, "B"); + lruCache.put(3, "C"); + + assertEquals("A", lruCache.get(1)); + assertEquals("B", lruCache.get(2)); + assertEquals("C", lruCache.get(3)); + } + + @Test + void testEvictionPolicy() { + lruCache.put(1, "A"); + lruCache.put(2, "B"); + lruCache.put(3, "C"); + lruCache.get(1); + lruCache.put(4, "D"); + + assertNull(lruCache.get(2)); + assertEquals("A", lruCache.get(1)); + } + + @Test + void testSize() { + lruCache.put(1, "A"); + lruCache.put(2, "B"); + + assertEquals(2, lruCache.size()); + } + + @Test + void testIsEmpty() { + assertTrue(lruCache.isEmpty()); + + lruCache.put(1, "A"); + + assertFalse(lruCache.isEmpty()); + } + + @Test + void testRemove() { + lruCache.put(1, "A"); + lruCache.remove(1); + + assertNull(lruCache.get(1)); + } + + @Test + void testContainsKey() { + lruCache.put(1, "A"); + + assertTrue(lruCache.containsKey(1)); + assertFalse(lruCache.containsKey(2)); + } + + @Test + void testContainsValue() { + lruCache.put(1, "A"); + + assertTrue(lruCache.containsValue("A")); + assertFalse(lruCache.containsValue("B")); + } + + @Test + void testKeySet() { + lruCache.put(1, "A"); + lruCache.put(2, "B"); + + assertTrue(lruCache.keySet().contains(1)); + assertTrue(lruCache.keySet().contains(2)); + } + + @Test + void testValues() { + lruCache.put(1, "A"); + lruCache.put(2, "B"); + + assertTrue(lruCache.values().contains("A")); + assertTrue(lruCache.values().contains("B")); + } + + @Test + void testClear() { + lruCache.put(1, "A"); + lruCache.put(2, "B"); + lruCache.clear(); + + assertTrue(lruCache.isEmpty()); + } + + @Test + void testPutAll() { + Map map = new LinkedHashMap<>(); + map.put(1, "A"); + map.put(2, "B"); + lruCache.putAll(map); + + assertEquals("A", lruCache.get(1)); + assertEquals("B", lruCache.get(2)); + } + + @Test + void testEntrySet() { + lruCache.put(1, "A"); + lruCache.put(2, "B"); + + assertEquals(2, lruCache.entrySet().size()); + } + + @Test + void testPutIfAbsent() { + lruCache.putIfAbsent(1, "A"); + lruCache.putIfAbsent(1, "B"); + + assertEquals("A", lruCache.get(1)); + } + + @Test + void testConcurrency() throws InterruptedException { + ExecutorService service = Executors.newFixedThreadPool(3); + + // Perform a mix of put and get operations from multiple threads + for (int i = 0; i < 10000; i++) { + final int key = i % 3; // Keys will be 0, 1, 2 + final String value = "Value" + i; + + service.submit(() -> lruCache.put(key, value)); + service.submit(() -> lruCache.get(key)); + } + + service.shutdown(); + assertTrue(service.awaitTermination(1, TimeUnit.MINUTES)); + + // Assert the final state of the cache + assertEquals(3, lruCache.size()); + Set keys = lruCache.keySet(); + assertTrue(keys.contains(0) || keys.contains(1) || keys.contains(2)); + } +} diff --git a/src/test/java/com/cedarsoftware/util/TestIO.java b/src/test/java/com/cedarsoftware/util/TestIO.java index 3c6bd8fa..b69938f8 100644 --- a/src/test/java/com/cedarsoftware/util/TestIO.java +++ b/src/test/java/com/cedarsoftware/util/TestIO.java @@ -2,7 +2,11 @@ import org.junit.jupiter.api.Test; -import java.io.*; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.OutputStreamWriter; import java.nio.charset.StandardCharsets; import java.util.HashSet; import java.util.Set; @@ -12,7 +16,7 @@ public class TestIO @Test public void testFastReader() throws Exception { - String content = TestUtilTest.fetchResource("prettyPrint.json"); + String content = TestUtil.fetchResource("prettyPrint.json"); ByteArrayInputStream bin = new ByteArrayInputStream(content.getBytes(StandardCharsets.UTF_8)); FastReader reader = new FastReader(new InputStreamReader(bin, StandardCharsets.UTF_8), 1024,10); assert reader.read() == '{'; @@ -54,7 +58,7 @@ public void testFastReader() throws Exception @Test public void testFastWriter() throws Exception { - String content = TestUtilTest.fetchResource("prettyPrint.json"); + String content = TestUtil.fetchResource("prettyPrint.json"); ByteArrayInputStream bin = new ByteArrayInputStream(content.getBytes(StandardCharsets.UTF_8)); FastReader reader = new FastReader(new InputStreamReader(bin, StandardCharsets.UTF_8), 1024,10); @@ -77,7 +81,7 @@ public void testFastWriter() throws Exception @Test public void testFastWriterCharBuffer() throws Exception { - String content = TestUtilTest.fetchResource("prettyPrint.json"); + String content = TestUtil.fetchResource("prettyPrint.json"); ByteArrayInputStream bin = new ByteArrayInputStream(content.getBytes(StandardCharsets.UTF_8)); FastReader reader = new FastReader(new InputStreamReader(bin, StandardCharsets.UTF_8), 1024,10); @@ -100,7 +104,7 @@ public void testFastWriterCharBuffer() throws Exception @Test public void testFastWriterString() throws Exception { - String content = TestUtilTest.fetchResource("prettyPrint.json"); + String content = TestUtil.fetchResource("prettyPrint.json"); ByteArrayInputStream bin = new ByteArrayInputStream(content.getBytes(StandardCharsets.UTF_8)); FastReader reader = new FastReader(new InputStreamReader(bin, StandardCharsets.UTF_8), 1024,10); diff --git a/src/test/java/com/cedarsoftware/util/TestUtilTest.java b/src/test/java/com/cedarsoftware/util/TestUtilTest.java index 2143f95b..1375ee6c 100644 --- a/src/test/java/com/cedarsoftware/util/TestUtilTest.java +++ b/src/test/java/com/cedarsoftware/util/TestUtilTest.java @@ -2,11 +2,6 @@ import org.junit.jupiter.api.Test; -import java.net.URL; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; - /** * @author John DeRegnaucourt (jdereg@gmail.com) *
@@ -56,18 +51,4 @@ public void testContains() assert !TestUtil.checkContainsIgnoreCase("This is the source string to test.", "Source", "string", "Text"); assert !TestUtil.checkContainsIgnoreCase("This is the source string to test.", "Test", "Source", "string"); } - - public static String fetchResource(String name) - { - try - { - URL url = TestUtil.class.getResource("/" + name); - Path resPath = Paths.get(url.toURI()); - return new String(Files.readAllBytes(resPath)); - } - catch (Exception e) - { - throw new RuntimeException(e); - } - } }