Repository navigation
Expand file tree
/
Copy pathtest_java_concurrency.py
More file actions
1356 lines (1155 loc) · 40.9 KB
/
Copy pathtest_java_concurrency.py
File metadata and controls
1356 lines (1155 loc) · 40.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Java concurrency and threading parsing testing.
Tests synchronized, volatile, locks, concurrent collections, CompletableFuture,
thread-safe constructs, and parallel processing patterns.
"""
from pathlib import Path
from unittest.mock import MagicMock
import pytest
from codebase_rag.graph_updater import GraphUpdater
from codebase_rag.parser_loader import load_parsers
@pytest.fixture
def java_concurrency_project(temp_repo: Path) -> Path:
"""Create a Java project for testing concurrency features."""
project_path = temp_repo / "java_concurrency_test"
project_path.mkdir()
# Create standard Java project structure
(project_path / "src").mkdir()
(project_path / "src" / "main").mkdir()
(project_path / "src" / "main" / "java").mkdir()
(project_path / "src" / "main" / "java" / "com").mkdir()
(project_path / "src" / "main" / "java" / "com" / "example").mkdir()
return project_path
def test_synchronized_methods_blocks(
java_concurrency_project: Path,
mock_ingestor: MagicMock,
) -> None:
"""Test Java synchronized methods and blocks parsing."""
test_file = (
java_concurrency_project
/ "src"
/ "main"
/ "java"
/ "com"
/ "example"
/ "SynchronizedExample.java"
)
test_file.write_text(
"""
package com.example;
public class SynchronizedExample {
private int counter = 0;
private final Object lock = new Object();
private static int staticCounter = 0;
// Synchronized instance method
public synchronized void incrementCounter() {
counter++;
notifyAll(); // Can use wait/notify in synchronized context
}
// Synchronized static method
public static synchronized void incrementStaticCounter() {
staticCounter++;
}
public synchronized int getCounter() {
return counter;
}
public static synchronized int getStaticCounter() {
return staticCounter;
}
// Synchronized block on this
public void incrementWithBlock() {
synchronized (this) {
counter++;
System.out.println("Counter: " + counter);
}
}
// Synchronized block on custom object
public void incrementWithCustomLock() {
synchronized (lock) {
counter++;
try {
lock.wait(1000); // Wait with timeout
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
// Synchronized block on class
public void incrementWithClassLock() {
synchronized (SynchronizedExample.class) {
staticCounter++;
}
}
// Multiple synchronized blocks
public void multipleBlocks() {
synchronized (this) {
counter++;
}
synchronized (lock) {
counter *= 2;
}
synchronized (SynchronizedExample.class) {
staticCounter += counter;
}
}
// Nested synchronized blocks
public void nestedSynchronized() {
synchronized (this) {
counter++;
synchronized (lock) {
counter += 10;
System.out.println("Nested synchronized: " + counter);
}
}
}
// Producer-Consumer pattern with wait/notify
private volatile boolean produced = false;
private String data;
public synchronized void produce(String value) throws InterruptedException {
while (produced) {
wait(); // Wait until consumed
}
data = value;
produced = true;
notifyAll(); // Notify consumers
}
public synchronized String consume() throws InterruptedException {
while (!produced) {
wait(); // Wait until produced
}
String result = data;
produced = false;
notifyAll(); // Notify producers
return result;
}
}
"""
)
parsers, queries = load_parsers()
if "java" not in parsers:
pytest.skip("Java parser not available")
updater = GraphUpdater(
ingestor=mock_ingestor,
repo_path=java_concurrency_project,
parsers=parsers,
queries=queries,
)
updater.run()
# Verify the class was detected
project_name = java_concurrency_project.name
class_calls = [
call
for call in mock_ingestor.ensure_node_batch.call_args_list
if call[0][0] == "Class"
]
created_classes = {call[0][1]["qualified_name"] for call in class_calls}
expected_classes = {
f"{project_name}.src.main.java.com.example.SynchronizedExample.SynchronizedExample",
}
missing_classes = expected_classes - created_classes
assert not missing_classes, (
f"Missing expected classes: {sorted(list(missing_classes))}"
)
def test_volatile_fields(
java_concurrency_project: Path,
mock_ingestor: MagicMock,
) -> None:
"""Test Java volatile field parsing."""
test_file = (
java_concurrency_project
/ "src"
/ "main"
/ "java"
/ "com"
/ "example"
/ "VolatileExample.java"
)
test_file.write_text(
"""
package com.example;
public class VolatileExample {
private volatile boolean running = true;
private volatile int counter = 0;
private volatile String status = "IDLE";
private volatile double progress = 0.0;
// Static volatile fields
private static volatile boolean systemReady = false;
private static volatile long lastUpdateTime = 0L;
// Volatile array reference (array itself is not volatile)
private volatile int[] data;
private volatile String[] messages;
// Volatile object references
private volatile Thread workerThread;
private volatile java.util.concurrent.locks.Lock lock;
public void startWorker() {
running = true;
status = "STARTING";
workerThread = new Thread(() -> {
while (running) {
counter++;
progress = counter / 100.0;
if (counter % 10 == 0) {
status = "WORKING - " + counter;
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
break;
}
}
status = "STOPPED";
});
workerThread.start();
}
public void stopWorker() {
running = false; // Volatile write - visible to worker thread
status = "STOPPING";
if (workerThread != null) {
try {
workerThread.join(5000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
// Getters for volatile fields
public boolean isRunning() {
return running; // Volatile read
}
public int getCounter() {
return counter; // Volatile read
}
public String getStatus() {
return status; // Volatile read
}
public double getProgress() {
return progress; // Volatile read
}
// Static methods for static volatile fields
public static void setSystemReady() {
systemReady = true;
lastUpdateTime = System.currentTimeMillis();
}
public static boolean isSystemReady() {
return systemReady;
}
public static long getLastUpdateTime() {
return lastUpdateTime;
}
// Double-checked locking pattern with volatile
private static volatile VolatileExample instance;
public static VolatileExample getInstance() {
if (instance == null) {
synchronized (VolatileExample.class) {
if (instance == null) {
instance = new VolatileExample();
}
}
}
return instance;
}
// Volatile with arrays
public void updateData(int[] newData) {
data = newData.clone(); // Volatile write of array reference
}
public int[] getData() {
return data; // Volatile read of array reference
}
public void addMessage(String message) {
String[] current = messages; // Volatile read
if (current == null) {
messages = new String[]{message}; // Volatile write
} else {
String[] newMessages = new String[current.length + 1];
System.arraycopy(current, 0, newMessages, 0, current.length);
newMessages[current.length] = message;
messages = newMessages; // Volatile write
}
}
}
"""
)
parsers, queries = load_parsers()
if "java" not in parsers:
pytest.skip("Java parser not available")
updater = GraphUpdater(
ingestor=mock_ingestor,
repo_path=java_concurrency_project,
parsers=parsers,
queries=queries,
)
updater.run()
# Verify the class was detected
project_name = java_concurrency_project.name
class_calls = [
call
for call in mock_ingestor.ensure_node_batch.call_args_list
if call[0][0] == "Class"
]
created_classes = {call[0][1]["qualified_name"] for call in class_calls}
expected_classes = {
f"{project_name}.src.main.java.com.example.VolatileExample.VolatileExample",
}
missing_classes = expected_classes - created_classes
assert not missing_classes, (
f"Missing expected classes: {sorted(list(missing_classes))}"
)
def test_concurrent_collections(
java_concurrency_project: Path,
mock_ingestor: MagicMock,
) -> None:
"""Test Java concurrent collections parsing."""
test_file = (
java_concurrency_project
/ "src"
/ "main"
/ "java"
/ "com"
/ "example"
/ "ConcurrentCollections.java"
)
test_file.write_text(
"""
package com.example;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import java.util.*;
public class ConcurrentCollections {
// ConcurrentHashMap
private final ConcurrentMap<String, Integer> scores = new ConcurrentHashMap<>();
private final ConcurrentHashMap<String, List<String>> userGroups = new ConcurrentHashMap<>();
// ConcurrentLinkedQueue
private final Queue<String> messageQueue = new ConcurrentLinkedQueue<>();
// BlockingQueue implementations
private final BlockingQueue<Task> taskQueue = new ArrayBlockingQueue<>(100);
private final BlockingQueue<String> priorityQueue = new PriorityBlockingQueue<>();
private final BlockingQueue<Object> linkedQueue = new LinkedBlockingQueue<>();
private final BlockingQueue<String> synchronousQueue = new SynchronousQueue<>();
// CopyOnWriteArrayList and Set
private final List<String> observers = new CopyOnWriteArrayList<>();
private final Set<String> activeUsers = new CopyOnWriteArraySet<>();
// Atomic variables
private final AtomicInteger counter = new AtomicInteger(0);
private final AtomicLong timestamp = new AtomicLong();
private final AtomicBoolean initialized = new AtomicBoolean(false);
private final AtomicReference<String> status = new AtomicReference<>("IDLE");
// Concurrent operations with ConcurrentHashMap
public void updateScore(String player, int points) {
scores.compute(player, (key, currentScore) -> {
return (currentScore == null) ? points : currentScore + points;
});
}
public void addUserToGroup(String user, String group) {
userGroups.computeIfAbsent(group, k -> new CopyOnWriteArrayList<>()).add(user);
}
public void removeUserFromGroup(String user, String group) {
userGroups.computeIfPresent(group, (key, users) -> {
users.remove(user);
return users.isEmpty() ? null : users;
});
}
// Producer-Consumer with BlockingQueue
public void submitTask(Task task) throws InterruptedException {
taskQueue.put(task); // Blocks if queue is full
}
public Task takeTask() throws InterruptedException {
return taskQueue.take(); // Blocks if queue is empty
}
public boolean submitTaskNonBlocking(Task task) {
return taskQueue.offer(task); // Returns false if queue is full
}
public Task pollTask(long timeout, TimeUnit unit) throws InterruptedException {
return taskQueue.poll(timeout, unit); // Waits up to timeout
}
// Message processing
public void sendMessage(String message) {
messageQueue.offer(message);
notifyObservers("Message sent: " + message);
}
public void processMessages() {
String message;
while ((message = messageQueue.poll()) != null) {
System.out.println("Processing: " + message);
counter.incrementAndGet();
}
}
// Observer pattern with CopyOnWriteArrayList
public void addObserver(String observer) {
observers.add(observer);
}
public void removeObserver(String observer) {
observers.remove(observer);
}
public void notifyObservers(String event) {
// Safe iteration during concurrent modifications
for (String observer : observers) {
System.out.println("Notifying " + observer + ": " + event);
}
}
// Active users management
public void userLogin(String user) {
activeUsers.add(user);
timestamp.set(System.currentTimeMillis());
}
public void userLogout(String user) {
activeUsers.remove(user);
timestamp.set(System.currentTimeMillis());
}
public Set<String> getActiveUsers() {
return new HashSet<>(activeUsers); // Safe snapshot
}
// Atomic operations
public int getNextSequenceNumber() {
return counter.incrementAndGet();
}
public boolean initializeIfNotDone() {
return initialized.compareAndSet(false, true);
}
public void updateStatus(String newStatus) {
String oldStatus = status.getAndSet(newStatus);
System.out.println("Status changed from " + oldStatus + " to " + newStatus);
}
public boolean changeStatusIfCurrent(String expectedStatus, String newStatus) {
return status.compareAndSet(expectedStatus, newStatus);
}
// Batch operations
public void processBatchTasks(List<Task> tasks) throws InterruptedException {
for (Task task : tasks) {
taskQueue.put(task);
}
}
public List<Task> drainTasks() {
List<Task> drained = new ArrayList<>();
taskQueue.drainTo(drained);
return drained;
}
public List<Task> drainTasks(int maxElements) {
List<Task> drained = new ArrayList<>();
taskQueue.drainTo(drained, maxElements);
return drained;
}
// Statistics
public Map<String, Object> getStatistics() {
Map<String, Object> stats = new ConcurrentHashMap<>();
stats.put("totalScores", scores.size());
stats.put("totalGroups", userGroups.size());
stats.put("messagesQueued", messageQueue.size());
stats.put("tasksQueued", taskQueue.size());
stats.put("observerCount", observers.size());
stats.put("activeUserCount", activeUsers.size());
stats.put("counter", counter.get());
stats.put("timestamp", timestamp.get());
stats.put("initialized", initialized.get());
stats.put("status", status.get());
return stats;
}
}
class Task {
private final String id;
private final String description;
public Task(String id, String description) {
this.id = id;
this.description = description;
}
public String getId() { return id; }
public String getDescription() { return description; }
}
"""
)
parsers, queries = load_parsers()
if "java" not in parsers:
pytest.skip("Java parser not available")
updater = GraphUpdater(
ingestor=mock_ingestor,
repo_path=java_concurrency_project,
parsers=parsers,
queries=queries,
)
updater.run()
# Verify the classes were detected
project_name = java_concurrency_project.name
class_calls = [
call
for call in mock_ingestor.ensure_node_batch.call_args_list
if call[0][0] == "Class"
]
created_classes = {call[0][1]["qualified_name"] for call in class_calls}
expected_classes = {
f"{project_name}.src.main.java.com.example.ConcurrentCollections.ConcurrentCollections",
f"{project_name}.src.main.java.com.example.ConcurrentCollections.Task",
}
missing_classes = expected_classes - created_classes
assert not missing_classes, (
f"Missing expected classes: {sorted(list(missing_classes))}"
)
def test_executor_service_patterns(
java_concurrency_project: Path,
mock_ingestor: MagicMock,
) -> None:
"""Test Java ExecutorService and thread pool parsing."""
test_file = (
java_concurrency_project
/ "src"
/ "main"
/ "java"
/ "com"
/ "example"
/ "ExecutorExample.java"
)
test_file.write_text(
"""
package com.example;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.*;
public class ExecutorExample {
// Different types of executor services
private final ExecutorService fixedThreadPool = Executors.newFixedThreadPool(4);
private final ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
private final ScheduledExecutorService scheduledExecutor = Executors.newScheduledThreadPool(2);
private final ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
// Custom thread pool
private final ThreadPoolExecutor customExecutor = new ThreadPoolExecutor(
2, // core pool size
4, // maximum pool size
60L, TimeUnit.SECONDS, // keep alive time
new LinkedBlockingQueue<>(100), // work queue
new ThreadFactory() {
private final AtomicInteger threadNumber = new AtomicInteger(1);
@Override
public Thread newThread(Runnable r) {
Thread t = new Thread(r, "CustomThread-" + threadNumber.getAndIncrement());
t.setDaemon(false);
return t;
}
},
new ThreadPoolExecutor.CallerRunsPolicy() // rejection policy
);
// CompletionService for managing completed tasks
private final CompletionService<String> completionService =
new ExecutorCompletionService<>(fixedThreadPool);
// Submit tasks and get futures
public Future<String> submitTask(String taskName) {
return fixedThreadPool.submit(() -> {
Thread.sleep(1000); // Simulate work
return "Completed: " + taskName;
});
}
public List<Future<String>> submitMultipleTasks(List<String> taskNames) {
List<Future<String>> futures = new ArrayList<>();
for (String taskName : taskNames) {
Future<String> future = fixedThreadPool.submit(() -> {
Thread.sleep(500);
return "Batch completed: " + taskName;
});
futures.add(future);
}
return futures;
}
// Execute tasks without return values
public void executeRunnableTasks() {
for (int i = 0; i < 10; i++) {
final int taskId = i;
fixedThreadPool.execute(() -> {
System.out.println("Executing task " + taskId);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
}
}
// Scheduled tasks
public ScheduledFuture<?> schedulePeriodicTask() {
return scheduledExecutor.scheduleAtFixedRate(
() -> System.out.println("Periodic task at " + System.currentTimeMillis()),
0, // initial delay
5, // period
TimeUnit.SECONDS
);
}
public ScheduledFuture<String> scheduleDelayedTask() {
return scheduledExecutor.schedule(
() -> "Delayed task completed at " + System.currentTimeMillis(),
10, // delay
TimeUnit.SECONDS
);
}
// Bulk operations
public List<String> invokeAllTasks(List<String> taskNames) throws InterruptedException {
List<Callable<String>> callables = new ArrayList<>();
for (String taskName : taskNames) {
callables.add(() -> {
Thread.sleep(200);
return "Invoke all: " + taskName;
});
}
List<Future<String>> futures = fixedThreadPool.invokeAll(callables);
List<String> results = new ArrayList<>();
for (Future<String> future : futures) {
try {
results.add(future.get());
} catch (ExecutionException e) {
results.add("Error: " + e.getCause().getMessage());
}
}
return results;
}
public String invokeAnyTask(List<String> taskNames) throws InterruptedException, ExecutionException {
List<Callable<String>> callables = new ArrayList<>();
for (String taskName : taskNames) {
callables.add(() -> {
Thread.sleep((long) (Math.random() * 1000));
return "First completed: " + taskName;
});
}
return fixedThreadPool.invokeAny(callables);
}
// CompletionService usage
public void submitToCompletionService(List<String> taskNames) {
for (String taskName : taskNames) {
completionService.submit(() -> {
Thread.sleep((long) (Math.random() * 1000));
return "Completion service: " + taskName;
});
}
}
public List<String> pollCompletedTasks(int maxTasks) throws InterruptedException {
List<String> results = new ArrayList<>();
for (int i = 0; i < maxTasks; i++) {
Future<String> future = completionService.poll(1, TimeUnit.SECONDS);
if (future != null) {
try {
results.add(future.get());
} catch (ExecutionException e) {
results.add("Error: " + e.getCause().getMessage());
}
} else {
break; // No more completed tasks
}
}
return results;
}
// Graceful shutdown
public void shutdown() {
shutdownExecutor(fixedThreadPool, "FixedThreadPool");
shutdownExecutor(cachedThreadPool, "CachedThreadPool");
shutdownExecutor(scheduledExecutor, "ScheduledExecutor");
shutdownExecutor(singleThreadExecutor, "SingleThreadExecutor");
shutdownExecutor(customExecutor, "CustomExecutor");
}
private void shutdownExecutor(ExecutorService executor, String name) {
executor.shutdown();
try {
if (!executor.awaitTermination(60, TimeUnit.SECONDS)) {
System.out.println(name + " did not terminate gracefully, forcing shutdown");
executor.shutdownNow();
if (!executor.awaitTermination(60, TimeUnit.SECONDS)) {
System.err.println(name + " did not terminate");
}
}
} catch (InterruptedException e) {
executor.shutdownNow();
Thread.currentThread().interrupt();
}
}
// Error handling
public void handleTaskExceptions() {
Future<String> future = fixedThreadPool.submit(() -> {
if (Math.random() < 0.5) {
throw new RuntimeException("Random task failure");
}
return "Task succeeded";
});
try {
String result = future.get(5, TimeUnit.SECONDS);
System.out.println("Result: " + result);
} catch (TimeoutException e) {
System.err.println("Task timed out");
future.cancel(true);
} catch (ExecutionException e) {
System.err.println("Task failed: " + e.getCause().getMessage());
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
System.err.println("Task was interrupted");
}
}
}
"""
)
parsers, queries = load_parsers()
if "java" not in parsers:
pytest.skip("Java parser not available")
updater = GraphUpdater(
ingestor=mock_ingestor,
repo_path=java_concurrency_project,
parsers=parsers,
queries=queries,
)
updater.run()
# Verify the class was detected
project_name = java_concurrency_project.name
class_calls = [
call
for call in mock_ingestor.ensure_node_batch.call_args_list
if call[0][0] == "Class"
]
created_classes = {call[0][1]["qualified_name"] for call in class_calls}
expected_classes = {
f"{project_name}.src.main.java.com.example.ExecutorExample.ExecutorExample",
}
missing_classes = expected_classes - created_classes
assert not missing_classes, (
f"Missing expected classes: {sorted(list(missing_classes))}"
)
def test_completable_future_patterns(
java_concurrency_project: Path,
mock_ingestor: MagicMock,
) -> None:
"""Test Java CompletableFuture parsing."""
test_file = (
java_concurrency_project
/ "src"
/ "main"
/ "java"
/ "com"
/ "example"
/ "CompletableFutureExample.java"
)
test_file.write_text(
"""
package com.example;
import java.util.concurrent.*;
import java.util.*;
import java.util.function.*;
public class CompletableFutureExample {
private final ExecutorService executor = Executors.newFixedThreadPool(4);
// Basic CompletableFuture creation
public CompletableFuture<String> createSimpleFuture() {
return CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
return "Hello, World!";
});
}
public CompletableFuture<Void> createVoidFuture() {
return CompletableFuture.runAsync(() -> {
System.out.println("Running asynchronously");
});
}
// Chaining operations
public CompletableFuture<String> chainOperations(String input) {
return CompletableFuture
.supplyAsync(() -> input.toLowerCase())
.thenApply(s -> s.trim())
.thenApply(s -> s.toUpperCase())
.thenApply(s -> "Result: " + s);
}
public CompletableFuture<Void> chainWithConsumer(String input) {
return CompletableFuture
.supplyAsync(() -> input.length())
.thenAccept(length -> System.out.println("Length: " + length))
.thenRun(() -> System.out.println("Processing complete"));
}
// Composing futures
public CompletableFuture<String> composeFutures(String input) {
return CompletableFuture
.supplyAsync(() -> input)
.thenCompose(s -> CompletableFuture.supplyAsync(() -> s.toUpperCase()))
.thenCompose(s -> CompletableFuture.supplyAsync(() -> "Composed: " + s));
}
// Combining futures
public CompletableFuture<String> combineFutures(String input1, String input2) {
CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> input1.toUpperCase());
CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> input2.toLowerCase());
return future1.thenCombine(future2, (s1, s2) -> s1 + " + " + s2);
}
// Exception handling
public CompletableFuture<String> handleExceptions(boolean shouldFail) {
return CompletableFuture
.supplyAsync(() -> {
if (shouldFail) {
throw new RuntimeException("Intentional failure");
}
return "Success";
})
.exceptionally(throwable -> "Failed: " + throwable.getMessage())
.handle((result, throwable) -> {
if (throwable != null) {
return "Handled: " + throwable.getMessage();
}
return "Completed: " + result;
});
}
public CompletableFuture<String> handleWithCompletion(boolean shouldFail) {
return CompletableFuture
.supplyAsync(() -> {
if (shouldFail) {
throw new RuntimeException("Failure");
}
return "Success";
})
.whenComplete((result, throwable) -> {
if (throwable != null) {
System.err.println("Error occurred: " + throwable.getMessage());
} else {
System.out.println("Success: " + result);
}
});
}
// Multiple futures operations
public CompletableFuture<Void> waitForAll(List<String> inputs) {
List<CompletableFuture<String>> futures = inputs.stream()
.map(input -> CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
return input.toUpperCase();
}))
.toList();
CompletableFuture<Void> allOf = CompletableFuture.allOf(
futures.toArray(new CompletableFuture[0])
);
return allOf.thenRun(() -> {
System.out.println("All futures completed");
futures.forEach(future -> {
try {
System.out.println("Result: " + future.get());
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
});
});
}
public CompletableFuture<Object> waitForAny(List<String> inputs) {
List<CompletableFuture<String>> futures = inputs.stream()
.map(input -> CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep((long) (Math.random() * 1000));
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
return "Completed: " + input;
}))
.toList();
return CompletableFuture.anyOf(futures.toArray(new CompletableFuture[0]));
}