• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 #![cfg(feature = "invocation")]
2 
3 use std::{
4     sync::{Arc, Barrier},
5     thread::spawn,
6 };
7 
8 use jni::{sys::jint, Executor};
9 
10 mod util;
11 use util::{jvm, AtomicIntegerProxy};
12 
13 #[test]
single_thread()14 fn single_thread() {
15     let executor = Executor::new(jvm().clone());
16     test_single_thread(executor);
17 }
18 
19 #[test]
serialized_threads()20 fn serialized_threads() {
21     let executor = Executor::new(jvm().clone());
22     test_serialized_threads(executor);
23 }
24 
25 #[test]
concurrent_threads()26 fn concurrent_threads() {
27     let executor = Executor::new(jvm().clone());
28     const THREAD_NUM: usize = 8;
29     test_concurrent_threads(executor, THREAD_NUM)
30 }
31 
test_single_thread(executor: Executor)32 fn test_single_thread(executor: Executor) {
33     let mut atomic = AtomicIntegerProxy::new(executor, 0).unwrap();
34     assert_eq!(0, atomic.get().unwrap());
35     assert_eq!(1, atomic.increment_and_get().unwrap());
36     assert_eq!(3, atomic.add_and_get(2).unwrap());
37     assert_eq!(3, atomic.get().unwrap());
38 }
39 
test_serialized_threads(executor: Executor)40 fn test_serialized_threads(executor: Executor) {
41     let mut atomic = AtomicIntegerProxy::new(executor, 0).unwrap();
42     assert_eq!(0, atomic.get().unwrap());
43     let jh = spawn(move || {
44         assert_eq!(1, atomic.increment_and_get().unwrap());
45         assert_eq!(3, atomic.add_and_get(2).unwrap());
46         atomic
47     });
48     let mut atomic = jh.join().unwrap();
49     assert_eq!(3, atomic.get().unwrap());
50 }
51 
test_concurrent_threads(executor: Executor, thread_num: usize)52 fn test_concurrent_threads(executor: Executor, thread_num: usize) {
53     const ITERS_PER_THREAD: usize = 10_000;
54 
55     let mut atomic = AtomicIntegerProxy::new(executor, 0).unwrap();
56     let barrier = Arc::new(Barrier::new(thread_num));
57     let mut threads = Vec::new();
58 
59     for _ in 0..thread_num {
60         let barrier = Arc::clone(&barrier);
61         let mut atomic = atomic.clone();
62         let jh = spawn(move || {
63             barrier.wait();
64             for _ in 0..ITERS_PER_THREAD {
65                 atomic.increment_and_get().unwrap();
66             }
67         });
68         threads.push(jh);
69     }
70     for jh in threads {
71         jh.join().unwrap();
72     }
73     let expected = (ITERS_PER_THREAD * thread_num) as jint;
74     assert_eq!(expected, atomic.get().unwrap());
75 }
76