Skip to content

Commit

Permalink
Added LRUCache and ClassUtilities.
Browse files Browse the repository at this point in the history
  • Loading branch information
jdereg committed Nov 12, 2023
1 parent 23dbef1 commit 8921bc1
Show file tree
Hide file tree
Showing 11 changed files with 556 additions and 28 deletions.
10 changes: 7 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,23 +7,23 @@ 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 <b>no dependencies</b> 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`).

---
To include in your project:
##### Gradle
```
implementation 'com.cedarsoftware:java-util:2.3.0'
implementation 'com.cedarsoftware:java-util:2.4.0'
```

##### Maven
```
<dependency>
<groupId>com.cedarsoftware</groupId>
<artifactId>java-util</artifactId>
<version>2.3.0</version>
<version>2.4.0</version>
</dependency>
```
---
Expand All @@ -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()`.
Expand All @@ -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.
Expand Down
3 changes: 3 additions & 0 deletions changelog.md
Original file line number Diff line number Diff line change
@@ -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.
Expand Down
2 changes: 1 addition & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
<groupId>com.cedarsoftware</groupId>
<artifactId>java-util</artifactId>
<packaging>jar</packaging>
<version>2.3.0</version>
<version>2.4.0</version>
<description>Java Utilities</description>
<url>https://github.com/jdereg/java-util</url>

Expand Down
145 changes: 145 additions & 0 deletions src/main/java/com/cedarsoftware/util/ClassUtilities.java
Original file line number Diff line number Diff line change
@@ -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.
* <p>
* @author John DeRegnaucourt ([email protected])
* <br>
* Copyright (c) Cedar Software LLC
* <br><br>
* 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
* <br><br>
* http://www.apache.org/licenses/LICENSE-2.0
* <br><br>
* 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<Class<?>> 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<Class<?>> queue = new LinkedList<>();
Set<Class<?>> 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);
}
}
}
21 changes: 21 additions & 0 deletions src/main/java/com/cedarsoftware/util/FastReader.java
Original file line number Diff line number Diff line change
Expand Up @@ -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.
* <p>
* @author John DeRegnaucourt ([email protected])
* <br>
* Copyright (c) Cedar Software LLC
* <br><br>
* 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
* <br><br>
* http://www.apache.org/licenses/LICENSE-2.0
* <br><br>
* 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;
Expand Down
21 changes: 21 additions & 0 deletions src/main/java/com/cedarsoftware/util/FastWriter.java
Original file line number Diff line number Diff line change
Expand Up @@ -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.
* <p>
* @author John DeRegnaucourt ([email protected])
* <br>
* Copyright (c) Cedar Software LLC
* <br><br>
* 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
* <br><br>
* http://www.apache.org/licenses/LICENSE-2.0
* <br><br>
* 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;

Expand Down
Loading

0 comments on commit 8921bc1

Please sign in to comment.