1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.maven.project;
20
21 import java.util.ArrayList;
22 import java.util.LinkedHashSet;
23 import java.util.List;
24 import java.util.Set;
25 import java.util.concurrent.CountDownLatch;
26 import java.util.concurrent.ExecutionException;
27 import java.util.concurrent.ExecutorService;
28 import java.util.concurrent.Executors;
29 import java.util.concurrent.Future;
30 import java.util.concurrent.TimeUnit;
31 import java.util.concurrent.atomic.AtomicInteger;
32 import java.util.concurrent.locks.LockSupport;
33
34 import org.apache.maven.artifact.Artifact;
35 import org.apache.maven.artifact.DefaultArtifact;
36 import org.junit.jupiter.api.Test;
37
38 import static org.junit.jupiter.api.Assertions.assertEquals;
39 import static org.junit.jupiter.api.Assertions.assertFalse;
40
41 class MavenProjectGetArtifactsTest {
42
43 @Test
44 void concurrentGetArtifactsDoesNotExposeAHalfBuiltSet() throws Exception {
45 MavenProject project = new MavenProject();
46 Set<Artifact> resolved = new LinkedHashSet<>();
47 for (int i = 0; i < 200; i++) {
48 resolved.add(new DefaultArtifact("g", "a" + i, "1", "compile", "jar", "", null));
49 }
50 project.setResolvedArtifacts(resolved);
51 project.setArtifactFilter(artifact -> {
52 LockSupport.parkNanos(TimeUnit.MICROSECONDS.toNanos(50));
53 return true;
54 });
55
56 int readers = 4;
57 ExecutorService pool = Executors.newFixedThreadPool(readers);
58 CountDownLatch start = new CountDownLatch(1);
59 List<Future<?>> futures = new ArrayList<>();
60 try {
61 for (int i = 0; i < readers; i++) {
62 futures.add(pool.submit(() -> {
63 start.await();
64 Set<Artifact> artifacts = project.getArtifacts();
65 assertEquals(resolved.size(), artifacts.size());
66 AtomicInteger seen = new AtomicInteger();
67 artifacts.forEach(artifact -> seen.incrementAndGet());
68 assertEquals(resolved.size(), seen.get());
69 return null;
70 }));
71 }
72 start.countDown();
73 for (Future<?> future : futures) {
74 try {
75 future.get(30, TimeUnit.SECONDS);
76 } catch (ExecutionException e) {
77 throw e.getCause() instanceof Exception ? (Exception) e.getCause() : e;
78 }
79 }
80 } finally {
81 pool.shutdownNow();
82 }
83
84 assertFalse(project.getArtifacts().isEmpty());
85 assertEquals(resolved.size(), project.getArtifacts().size());
86 }
87 }