1/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17import java.lang.reflect.Method;
18import java.lang.reflect.Type;
19import java.util.ArrayList;
20import java.util.List;
21import java.util.concurrent.Callable;
22import java.util.concurrent.Executors;
23import java.util.concurrent.ExecutorService;
24import java.util.concurrent.Future;
25import java.util.concurrent.TimeUnit;
26import java.util.concurrent.CancellationException;
27import java.util.concurrent.TimeoutException;
28
29public class Main {
30
31  // Workaround for b/18051191.
32  class InnerClass {}
33
34  private static class HashCodeQuery implements Callable<Integer> {
35    public HashCodeQuery(Object obj) {
36      m_obj = obj;
37    }
38
39    public Integer call() {
40      Integer result;
41      try {
42        Class<?> c = Class.forName("Test");
43        Method m = c.getMethod("synchronizedHashCode", new Class[] { Object.class });
44        result = (Integer) m.invoke(null, m_obj);
45      } catch (Exception e) {
46        System.err.println("Hash code query exception");
47        e.printStackTrace();
48        result = -1;
49      }
50      return result;
51    }
52
53    private Object m_obj;
54    private int m_index;
55  }
56
57  public static void main(String args[]) throws Exception {
58    Object obj = new Object();
59    int numThreads = 10;
60
61    ExecutorService pool = Executors.newFixedThreadPool(numThreads);
62
63    List<HashCodeQuery> queries = new ArrayList<HashCodeQuery>(numThreads);
64    for (int i = 0; i < numThreads; ++i) {
65      queries.add(new HashCodeQuery(obj));
66    }
67
68    try {
69      List<Future<Integer>> results = pool.invokeAll(queries, 5, TimeUnit.SECONDS);
70
71      int hash = obj.hashCode();
72      for (int i = 0; i < numThreads; ++i) {
73        int result = results.get(i).get();
74        if (hash != result) {
75          throw new Error("Query #" + i + " wrong. Expected " + hash + ", got " + result);
76        }
77      }
78      pool.shutdown();
79    } catch (CancellationException ex) {
80      System.err.println("Job timeout");
81      System.exit(1);
82    }
83  }
84}
85