From 1d5dbcaaf447d1142958428ae57a19815259f066 Mon Sep 17 00:00:00 2001 From: Jacob Abrams Date: Mon, 8 Mar 2021 14:35:44 -0800 Subject: [PATCH] Make FileUtils#createDir threadsafe Prior to this change the createDir method would return false if invoked around the same time on two different threads for the same directory. Test: manual Change-Id: I34ba4f645a034f47917054af4b299f916a9cfa67 --- core/java/android/os/FileUtils.java | 20 +++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/core/java/android/os/FileUtils.java b/core/java/android/os/FileUtils.java index a4d6c3845fbfc..0264d2335c4bf 100644 --- a/core/java/android/os/FileUtils.java +++ b/core/java/android/os/FileUtils.java @@ -1235,9 +1235,9 @@ public final class FileUtils { } /** - * Creates a directory with name {@code name} under an existing directory {@code baseDir}. - * Returns a {@code File} object representing the directory on success, {@code null} on - * failure. + * Creates a directory with name {@code name} under an existing directory {@code baseDir} if it + * doesn't exist already. Returns a {@code File} object representing the directory if it exists + * and {@code null} if not. * * @hide */ @@ -1247,13 +1247,23 @@ public final class FileUtils { return createDir(dir) ? dir : null; } - /** @hide */ + /** + * Ensure the given directory exists, creating it if needed. This method is threadsafe. + * + * @return false if the directory doesn't exist and couldn't be created + * + * @hide + */ public static boolean createDir(File dir) { + if (dir.mkdir()) { + return true; + } + if (dir.exists()) { return dir.isDirectory(); } - return dir.mkdir(); + return false; } /**