Skip to content

Commit 97e96e6

Browse files
committed
Use move strategy to be thread safe for file creation as well
1 parent 5d84566 commit 97e96e6

File tree

1 file changed

+17
-5
lines changed

1 file changed

+17
-5
lines changed

common/utils/src/main/java/org/graalvm/buildtools/agent/AgentConfiguration.java

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -138,26 +138,38 @@ private void addDefaultAccessFilter() {
138138
return;
139139
}
140140

141+
String accessFilterPrefix = "access-filter";
142+
String accessFilterSuffix = ".json";
143+
141144
String tempDir = System.getProperty("java.io.tmpdir");
142145
Path agentDir = Path.of(tempDir).resolve("agent-config");
143-
Path accessFilterFile = agentDir.resolve("access-filter.json");
146+
Path accessFilterFile = agentDir.resolve(accessFilterPrefix + accessFilterSuffix);
144147
if (Files.exists(accessFilterFile)) {
145148
accessFilterFiles.add(accessFilterFile.toString());
146149
return;
147150
}
148151

149-
try(InputStream accessFilter = AgentConfiguration.class.getResourceAsStream(DEFAULT_ACCESS_FILTER_FILE)) {
150-
if (accessFilter == null) {
152+
try(InputStream accessFilterData = AgentConfiguration.class.getResourceAsStream(DEFAULT_ACCESS_FILTER_FILE)) {
153+
if (accessFilterData == null) {
151154
throw new IOException("Cannot find access-filter.json on default location: " + DEFAULT_ACCESS_FILTER_FILE);
152155
}
153156

154157
try {
155158
Files.createDirectory(agentDir);
156159
} catch (FileAlreadyExistsException e) {
157-
System.out.println("Agent directory already exists probably because other thread or process created it.");
160+
System.out.println("Ignore directory creation because " + agentDir + " directory is already created.");
161+
}
162+
163+
Path tmpAccessFilter = Files.createTempFile(agentDir, accessFilterPrefix, accessFilterSuffix);
164+
Files.copy(accessFilterData, tmpAccessFilter);
165+
166+
try {
167+
Files.move(tmpAccessFilter, accessFilterFile, StandardCopyOption.ATOMIC_MOVE);
168+
} catch (FileAlreadyExistsException e) {
169+
Files.delete(tmpAccessFilter);
170+
System.out.println("Access-filter file already exists. Delete temporary one.");
158171
}
159172

160-
Files.copy(accessFilter, accessFilterFile, StandardCopyOption.REPLACE_EXISTING);
161173
accessFilterFiles.add(accessFilterFile.toString());
162174
} catch (IOException e) {
163175
throw new RuntimeException("Cannot add default access-filter.json" ,e);

0 commit comments

Comments
 (0)