8300977: Retire java.io.ExpiringCache

Reviewed-by: alanb, jpai
This commit is contained in:
Per Minborg 2023-03-28 13:15:19 +00:00
parent c90699eae7
commit 927e674c12
6 changed files with 32 additions and 434 deletions

@ -1,125 +0,0 @@
/*
* Copyright (c) 2002, 2023, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.io;
import java.util.Map;
import java.util.LinkedHashMap;
import java.util.Set;
final class ExpiringCache {
private static final int QUERY_OVERFLOW = 300;
private static final int MAX_ENTRIES = 200;
private final long millisUntilExpiration;
private final Map<String,Entry> map;
// Clear out old entries every few queries
private int queryCount;
static final class Entry {
private long timestamp;
private String val;
Entry(long timestamp, String val) {
this.timestamp = timestamp;
this.val = val;
}
long timestamp() { return timestamp; }
void setTimestamp(long timestamp) { this.timestamp = timestamp; }
String val() { return val; }
void setVal(String val) { this.val = val; }
}
ExpiringCache() {
this(30000);
}
@SuppressWarnings("serial")
ExpiringCache(long millisUntilExpiration) {
this.millisUntilExpiration = millisUntilExpiration;
map = new LinkedHashMap<>() {
protected boolean removeEldestEntry(Map.Entry<String,Entry> eldest) {
return size() > MAX_ENTRIES;
}
};
}
synchronized String get(String key) {
if (++queryCount >= QUERY_OVERFLOW) {
cleanup();
}
Entry entry = entryFor(key);
if (entry != null) {
return entry.val();
}
return null;
}
synchronized void put(String key, String val) {
if (++queryCount >= QUERY_OVERFLOW) {
cleanup();
}
Entry entry = entryFor(key);
if (entry != null) {
entry.setTimestamp(System.currentTimeMillis());
entry.setVal(val);
} else {
map.put(key, new Entry(System.currentTimeMillis(), val));
}
}
synchronized void clear() {
map.clear();
}
private Entry entryFor(String key) {
Entry entry = map.get(key);
if (entry != null) {
long delta = System.currentTimeMillis() - entry.timestamp();
if (delta < 0 || delta >= millisUntilExpiration) {
map.remove(key);
entry = null;
}
}
return entry;
}
private void cleanup() {
Set<String> keySet = map.keySet();
// Avoid ConcurrentModificationExceptions
String[] keys = new String[keySet.size()];
int i = 0;
for (String key: keySet) {
keys[i++] = key;
}
for (int j = 0; j < keys.length; j++) {
entryFor(keys[j]);
}
queryCount = 0;
}
}

@ -1,5 +1,5 @@
/*
* Copyright (c) 1998, 2022, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1998, 2023, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -243,18 +243,4 @@ abstract class FileSystem {
*/
public abstract int hashCode(File f);
// Flags for enabling/disabling performance optimizations for file
// name canonicalization
static final boolean useCanonCaches;
static final boolean useCanonPrefixCache;
private static boolean getBooleanProperty(String prop, boolean defaultVal) {
String value = System.getProperty(prop);
return (value != null) ? Boolean.parseBoolean(value) : defaultVal;
}
static {
useCanonCaches = getBooleanProperty("sun.io.useCanonCaches", false);
useCanonPrefixCache = useCanonCaches && getBooleanProperty("sun.io.useCanonPrefixCache", false);
}
}

@ -1,5 +1,5 @@
/*
* Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2012, 2023, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -29,7 +29,9 @@ package java.io;
*
* @since 1.8
*/
class DefaultFileSystem {
final class DefaultFileSystem {
private DefaultFileSystem() {}
/**
* Return the FileSystem object for Unix-based platform.

@ -1,5 +1,5 @@
/*
* Copyright (c) 1998, 2022, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1998, 2023, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -30,24 +30,19 @@ import jdk.internal.misc.Blocker;
import jdk.internal.util.StaticProperty;
import sun.security.action.GetPropertyAction;
class UnixFileSystem extends FileSystem {
final class UnixFileSystem extends FileSystem {
private final char slash;
private final char colon;
private final String javaHome;
private final String userDir;
public UnixFileSystem() {
UnixFileSystem() {
Properties props = GetPropertyAction.privilegedGetProperties();
slash = props.getProperty("file.separator").charAt(0);
colon = props.getProperty("path.separator").charAt(0);
javaHome = StaticProperty.javaHome();
userDir = StaticProperty.userDir();
cache = useCanonCaches ? new ExpiringCache() : null;
javaHomePrefixCache = useCanonPrefixCache ? new ExpiringCache() : null;
}
/* -- Normalization and construction -- */
@Override
@ -142,7 +137,7 @@ class UnixFileSystem extends FileSystem {
@Override
public boolean isInvalid(File f) {
return f.getPath().indexOf('\u0000') < 0 ? false : true;
return f.getPath().indexOf('\u0000') >= 0;
}
@Override
@ -156,117 +151,16 @@ class UnixFileSystem extends FileSystem {
return resolve(userDir, f.getPath());
}
// Caches for canonicalization results to improve startup performance.
// The first cache handles repeated canonicalizations of the same path
// name. The prefix cache handles repeated canonicalizations within the
// same directory, and must not create results differing from the true
// canonicalization algorithm in canonicalize_md.c. For this reason the
// prefix cache is conservative and is not used for complex path names.
private final ExpiringCache cache;
// On Unix symlinks can jump anywhere in the file system, so we only
// treat prefixes in java.home as trusted and cacheable in the
// canonicalization algorithm
private final ExpiringCache javaHomePrefixCache;
@Override
public String canonicalize(String path) throws IOException {
if (!useCanonCaches) {
long comp = Blocker.begin();
try {
return canonicalize0(path);
} finally {
Blocker.end(comp);
}
} else {
String res = cache.get(path);
if (res == null) {
String dir = null;
String resDir;
if (useCanonPrefixCache) {
// Note that this can cause symlinks that should
// be resolved to a destination directory to be
// resolved to the directory they're contained in
dir = parentOrNull(path);
if (dir != null) {
resDir = javaHomePrefixCache.get(dir);
if (resDir != null) {
// Hit only in prefix cache; full path is canonical
String filename = path.substring(1 + dir.length());
res = resDir + slash + filename;
cache.put(dir + slash + filename, res);
}
}
}
if (res == null) {
long comp = Blocker.begin();
try {
res = canonicalize0(path);
} finally {
Blocker.end(comp);
}
cache.put(path, res);
if (useCanonPrefixCache &&
dir != null && dir.startsWith(javaHome)) {
resDir = parentOrNull(res);
// Note that we don't allow a resolved symlink
// to elsewhere in java.home to pollute the
// prefix cache (java.home prefix cache could
// just as easily be a set at this point)
if (resDir != null && resDir.equals(dir)) {
File f = new File(res);
if (f.exists() && !f.isDirectory()) {
javaHomePrefixCache.put(dir, resDir);
}
}
}
}
}
return res;
long comp = Blocker.begin();
try {
return canonicalize0(path);
} finally {
Blocker.end(comp);
}
}
private native String canonicalize0(String path) throws IOException;
// Best-effort attempt to get parent of this path; used for
// optimization of filename canonicalization. This must return null for
// any cases where the code in canonicalize_md.c would throw an
// exception or otherwise deal with non-simple pathnames like handling
// of "." and "..". It may conservatively return null in other
// situations as well. Returning null will cause the underlying
// (expensive) canonicalization routine to be called.
static String parentOrNull(String path) {
if (path == null) return null;
char sep = File.separatorChar;
int last = path.length() - 1;
int idx = last;
int adjacentDots = 0;
int nonDotCount = 0;
while (idx > 0) {
char c = path.charAt(idx);
if (c == '.') {
if (++adjacentDots >= 2) {
// Punt on pathnames containing . and ..
return null;
}
} else if (c == sep) {
if (adjacentDots == 1 && nonDotCount == 0) {
// Punt on pathnames containing . and ..
return null;
}
if (idx == 0 ||
idx >= last - 1 ||
path.charAt(idx - 1) == sep) {
// Punt on pathnames containing adjacent slashes
// toward the end
return null;
}
return path.substring(0, idx);
} else {
++nonDotCount;
adjacentDots = 0;
}
--idx;
}
return null;
}
/* -- Attribute accessors -- */
@ -362,17 +256,6 @@ class UnixFileSystem extends FileSystem {
@Override
public boolean delete(File f) {
// Keep canonicalization caches in sync after file deletion
// and renaming operations. Could be more clever than this
// (i.e., only remove/update affected entries) but probably
// not worth it since these entries expire after 30 seconds
// anyway.
if (useCanonCaches) {
cache.clear();
}
if (useCanonPrefixCache) {
javaHomePrefixCache.clear();
}
long comp = Blocker.begin();
try {
return delete0(f);
@ -406,17 +289,6 @@ class UnixFileSystem extends FileSystem {
@Override
public boolean rename(File f1, File f2) {
// Keep canonicalization caches in sync after file deletion
// and renaming operations. Could be more clever than this
// (i.e., only remove/update affected entries) but probably
// not worth it since these entries expire after 30 seconds
// anyway.
if (useCanonCaches) {
cache.clear();
}
if (useCanonPrefixCache) {
javaHomePrefixCache.clear();
}
long comp = Blocker.begin();
try {
return rename0(f1, f2);
@ -500,7 +372,6 @@ class UnixFileSystem extends FileSystem {
return f.getPath().hashCode() ^ 1234321;
}
private static native void initIDs();
static {

@ -1,5 +1,5 @@
/*
* Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2012, 2023, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -29,7 +29,9 @@ package java.io;
*
* @since 1.8
*/
class DefaultFileSystem {
final class DefaultFileSystem {
private DefaultFileSystem() {}
/**
* Return the FileSystem object for Windows platform.

@ -25,7 +25,6 @@
package java.io;
import java.io.File;
import java.nio.file.InvalidPathException;
import java.nio.file.Path;
import java.util.BitSet;
@ -40,7 +39,7 @@ import sun.security.action.GetPropertyAction;
* @author Konstantin Kladko
* @since 1.4
*/
class WinNTFileSystem extends FileSystem {
final class WinNTFileSystem extends FileSystem {
private final char slash;
private final char altSlash;
@ -61,14 +60,12 @@ class WinNTFileSystem extends FileSystem {
}
}
public WinNTFileSystem() {
WinNTFileSystem() {
Properties props = GetPropertyAction.privilegedGetProperties();
slash = props.getProperty("file.separator").charAt(0);
semicolon = props.getProperty("path.separator").charAt(0);
altSlash = (this.slash == '\\') ? '/' : '\\';
userDir = normalize(props.getProperty("user.dir"));
cache = useCanonCaches ? new ExpiringCache() : null;
prefixCache = useCanonPrefixCache ? new ExpiringCache() : null;
}
private boolean isSlash(char c) {
@ -410,7 +407,7 @@ class WinNTFileSystem extends FileSystem {
return (pl == 3) ? path.substring(0, 2) : null;
}
private static String[] driveDirCache = new String[26];
private static final String[] DRIVE_DIR_CACHE = new String[26];
private static int driveIndex(char d) {
if ((d >= 'a') && (d <= 'z')) return d - 'a';
@ -423,21 +420,16 @@ class WinNTFileSystem extends FileSystem {
private String getDriveDirectory(char drive) {
int i = driveIndex(drive);
if (i < 0) return null;
String s = driveDirCache[i];
// Updates might not be visible to other threads so there
// is no guarantee getDriveDirectory(i+1) is called just once
// for any given value of i.
String s = DRIVE_DIR_CACHE[i];
if (s != null) return s;
s = getDriveDirectory(i + 1);
driveDirCache[i] = s;
DRIVE_DIR_CACHE[i] = s;
return s;
}
// Caches for canonicalization results to improve startup performance.
// The first cache handles repeated canonicalizations of the same path
// name. The prefix cache handles repeated canonicalizations within the
// same directory, and must not create results differing from the true
// canonicalization algorithm in canonicalize_md.c. For this reason the
// prefix cache is conservative and is not used for complex path names.
private final ExpiringCache cache;
private final ExpiringCache prefixCache;
}
@Override
public String canonicalize(String path) throws IOException {
@ -459,125 +451,17 @@ class WinNTFileSystem extends FileSystem {
return path;
return "" + ((char) (c-32)) + ':' + '\\';
}
if (!useCanonCaches) {
long comp = Blocker.begin();
try {
return canonicalize0(path);
} finally {
Blocker.end(comp);
}
} else {
String res = cache.get(path);
if (res == null) {
String dir = null;
String resDir = null;
if (useCanonPrefixCache) {
dir = parentOrNull(path);
if (dir != null) {
resDir = prefixCache.get(dir);
if (resDir != null) {
/*
* Hit only in prefix cache; full path is canonical,
* but we need to get the canonical name of the file
* in this directory to get the appropriate
* capitalization
*/
String filename = path.substring(1 + dir.length());
res = canonicalizeWithPrefix(resDir, filename);
cache.put(dir + File.separatorChar + filename, res);
}
}
}
if (res == null) {
res = canonicalize0(path);
cache.put(path, res);
if (useCanonPrefixCache && dir != null) {
resDir = parentOrNull(res);
if (resDir != null) {
File f = new File(res);
if (f.exists() && !f.isDirectory()) {
prefixCache.put(dir, resDir);
}
}
}
}
}
return res;
long comp = Blocker.begin();
try {
return canonicalize0(path);
} finally {
Blocker.end(comp);
}
}
private native String canonicalize0(String path)
throws IOException;
private String canonicalizeWithPrefix(String canonicalPrefix,
String filename) throws IOException
{
return canonicalizeWithPrefix0(canonicalPrefix,
canonicalPrefix + File.separatorChar + filename);
}
// Run the canonicalization operation assuming that the prefix
// (everything up to the last filename) is canonical; just gets
// the canonical name of the last element of the path
private native String canonicalizeWithPrefix0(String canonicalPrefix,
String pathWithCanonicalPrefix)
throws IOException;
// Best-effort attempt to get parent of this path; used for
// optimization of filename canonicalization. This must return null for
// any cases where the code in canonicalize_md.c would throw an
// exception or otherwise deal with non-simple pathnames like handling
// of "." and "..". It may conservatively return null in other
// situations as well. Returning null will cause the underlying
// (expensive) canonicalization routine to be called.
private static String parentOrNull(String path) {
if (path == null) return null;
char sep = File.separatorChar;
char altSep = '/';
int last = path.length() - 1;
int idx = last;
int adjacentDots = 0;
int nonDotCount = 0;
while (idx > 0) {
char c = path.charAt(idx);
if (c == '.') {
if (++adjacentDots >= 2) {
// Punt on pathnames containing . and ..
return null;
}
if (nonDotCount == 0) {
// Punt on pathnames ending in a .
return null;
}
} else if (c == sep) {
if (adjacentDots == 1 && nonDotCount == 0) {
// Punt on pathnames containing . and ..
return null;
}
if (idx == 0 ||
idx >= last - 1 ||
path.charAt(idx - 1) == sep ||
path.charAt(idx - 1) == altSep) {
// Punt on pathnames containing adjacent slashes
// toward the end
return null;
}
return path.substring(0, idx);
} else if (c == altSep) {
// Punt on pathnames containing both backward and
// forward slashes
return null;
} else if (c == '*' || c == '?') {
// Punt on pathnames containing wildcards
return null;
} else {
++nonDotCount;
adjacentDots = 0;
}
--idx;
}
return null;
}
/* -- Attribute accessors -- */
@ -695,17 +579,6 @@ class WinNTFileSystem extends FileSystem {
@Override
public boolean delete(File f) {
// Keep canonicalization caches in sync after file deletion
// and renaming operations. Could be more clever than this
// (i.e., only remove/update affected entries) but probably
// not worth it since these entries expire after 30 seconds
// anyway.
if (useCanonCaches) {
cache.clear();
}
if (useCanonPrefixCache) {
prefixCache.clear();
}
long comp = Blocker.begin();
try {
return delete0(f);
@ -717,17 +590,6 @@ class WinNTFileSystem extends FileSystem {
@Override
public boolean rename(File f1, File f2) {
// Keep canonicalization caches in sync after file deletion
// and renaming operations. Could be more clever than this
// (i.e., only remove/update affected entries) but probably
// not worth it since these entries expire after 30 seconds
// anyway.
if (useCanonCaches) {
cache.clear();
}
if (useCanonPrefixCache) {
prefixCache.clear();
}
long comp = Blocker.begin();
try {
return rename0(f1, f2);