Skip to content

Commit

Permalink
Lazily initialize DataSize.PATTERN
Browse files Browse the repository at this point in the history
To avoid unnecessary eager initialization of DataSize.PATTERN, this
commit initializes it lazily in the first invocation of DataSize.parse
by moving PATTERN to a private static nested class.

Closes gh-28560
  • Loading branch information
sbrannen committed Jun 3, 2022
1 parent aab9da0 commit e276737
Showing 1 changed file with 22 additions and 13 deletions.
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2020 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand Down Expand Up @@ -52,11 +52,6 @@
@SuppressWarnings("serial")
public final class DataSize implements Comparable<DataSize>, Serializable {

/**
* The pattern for parsing.
*/
private static final Pattern PATTERN = Pattern.compile("^([+\\-]?\\d+)([a-zA-Z]{0,2})$");

/**
* Bytes per Kilobyte.
*/
Expand Down Expand Up @@ -179,9 +174,9 @@ public static DataSize parse(CharSequence text) {
public static DataSize parse(CharSequence text, @Nullable DataUnit defaultUnit) {
Assert.notNull(text, "Text must not be null");
try {
Matcher matcher = PATTERN.matcher(text);
Matcher matcher = DataSizeUtils.PATTERN.matcher(text);
Assert.state(matcher.matches(), "Does not match data size pattern");
DataUnit unit = determineDataUnit(matcher.group(2), defaultUnit);
DataUnit unit = DataSizeUtils.determineDataUnit(matcher.group(2), defaultUnit);
long amount = Long.parseLong(matcher.group(1));
return DataSize.of(amount, unit);
}
Expand All @@ -190,11 +185,6 @@ public static DataSize parse(CharSequence text, @Nullable DataUnit defaultUnit)
}
}

private static DataUnit determineDataUnit(String suffix, @Nullable DataUnit defaultUnit) {
DataUnit defaultUnitToUse = (defaultUnit != null ? defaultUnit : DataUnit.BYTES);
return (StringUtils.hasLength(suffix) ? DataUnit.fromSuffix(suffix) : defaultUnitToUse);
}

/**
* Checks if this size is negative, excluding zero.
* @return true if this size has a size less than zero bytes
Expand Down Expand Up @@ -271,4 +261,23 @@ public int hashCode() {
return Long.hashCode(this.bytes);
}


/**
* Static nested class to support lazy loading of the {@link #PATTERN}.
* @since 5.3.21
*/
private static class DataSizeUtils {

/**
* The pattern for parsing.
*/
private static final Pattern PATTERN = Pattern.compile("^([+\\-]?\\d+)([a-zA-Z]{0,2})$");

private static DataUnit determineDataUnit(String suffix, @Nullable DataUnit defaultUnit) {
DataUnit defaultUnitToUse = (defaultUnit != null ? defaultUnit : DataUnit.BYTES);
return (StringUtils.hasLength(suffix) ? DataUnit.fromSuffix(suffix) : defaultUnitToUse);
}

}

}

0 comments on commit e276737

Please sign in to comment.