PageRenderTime 47ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 1ms

/test/java/util/concurrent/locks/Lock/TimedAcquireLeak.java

https://bitbucket.org/psandoz/lambda-jdk
Java | 272 lines | 188 code | 32 blank | 52 comment | 17 complexity | e50c933ba95002ee6cad61099a7273b5 MD5 | raw file
Possible License(s): BSD-3-Clause-No-Nuclear-License-2014, LGPL-3.0, GPL-2.0
  1. /*
  2. * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
  3. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  4. *
  5. * This code is free software; you can redistribute it and/or modify it
  6. * under the terms of the GNU General Public License version 2 only, as
  7. * published by the Free Software Foundation.
  8. *
  9. * This code is distributed in the hope that it will be useful, but WITHOUT
  10. * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11. * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
  12. * version 2 for more details (a copy is included in the LICENSE file that
  13. * accompanied this code).
  14. *
  15. * You should have received a copy of the GNU General Public License version
  16. * 2 along with this work; if not, write to the Free Software Foundation,
  17. * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18. *
  19. * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20. * or visit www.oracle.com if you need additional information or have any
  21. * questions.
  22. */
  23. /*
  24. * @test
  25. * @bug 6460501 6236036 6500694 6490770
  26. * @summary Repeated failed timed waits shouldn't leak memory
  27. * @author Martin Buchholz
  28. */
  29. // Note: this file is now out of sync with the jsr166 CVS repository due to the fix for 7092140
  30. import java.util.*;
  31. import java.util.regex.*;
  32. import java.util.concurrent.*;
  33. import java.util.concurrent.locks.*;
  34. import static java.util.concurrent.TimeUnit.*;
  35. import java.io.*;
  36. public class TimedAcquireLeak {
  37. static String javahome() {
  38. String jh = System.getProperty("java.home");
  39. return (jh.endsWith("jre")) ? jh.substring(0, jh.length() - 4) : jh;
  40. }
  41. static final File bin = new File(javahome(), "bin");
  42. static String javaProgramPath(String programName) {
  43. return new File(bin, programName).getPath();
  44. }
  45. static final String java = javaProgramPath("java");
  46. static final String jmap = javaProgramPath("jmap");
  47. static final String jps = javaProgramPath("jps");
  48. static String outputOf(Reader r) throws IOException {
  49. final StringBuilder sb = new StringBuilder();
  50. final char[] buf = new char[1024];
  51. int n;
  52. while ((n = r.read(buf)) > 0)
  53. sb.append(buf, 0, n);
  54. return sb.toString();
  55. }
  56. static String outputOf(InputStream is) throws IOException {
  57. return outputOf(new InputStreamReader(is, "UTF-8"));
  58. }
  59. static final ExecutorService drainers = Executors.newFixedThreadPool(12);
  60. static Future<String> futureOutputOf(final InputStream is) {
  61. return drainers.submit(
  62. new Callable<String>() { public String call() throws IOException {
  63. return outputOf(is); }});}
  64. static String outputOf(final Process p) {
  65. try {
  66. Future<String> outputFuture = futureOutputOf(p.getInputStream());
  67. Future<String> errorFuture = futureOutputOf(p.getErrorStream());
  68. final String output = outputFuture.get();
  69. final String error = errorFuture.get();
  70. // Check for successful process completion
  71. equal(error, "");
  72. equal(p.waitFor(), 0);
  73. equal(p.exitValue(), 0);
  74. return output;
  75. } catch (Throwable t) { unexpected(t); throw new Error(t); }
  76. }
  77. static String commandOutputOf(String... cmd) {
  78. try { return outputOf(new ProcessBuilder(cmd).start()); }
  79. catch (Throwable t) { unexpected(t); throw new Error(t); }
  80. }
  81. // To be called exactly twice by the parent process
  82. static <T> T rendezvousParent(Process p,
  83. Callable<T> callable) throws Throwable {
  84. p.getInputStream().read();
  85. T result = callable.call();
  86. OutputStream os = p.getOutputStream();
  87. os.write((byte)'\n'); os.flush();
  88. return result;
  89. }
  90. // To be called exactly twice by the child process
  91. public static void rendezvousChild() {
  92. try {
  93. for (int i = 0; i < 100; i++) {
  94. System.gc(); System.runFinalization(); Thread.sleep(50);
  95. }
  96. System.out.write((byte)'\n'); System.out.flush();
  97. System.in.read();
  98. } catch (Throwable t) { throw new Error(t); }
  99. }
  100. static String match(String s, String regex, int group) {
  101. Matcher matcher = Pattern.compile(regex).matcher(s);
  102. matcher.find();
  103. return matcher.group(group);
  104. }
  105. static int objectsInUse(final Process child,
  106. final String childPid,
  107. final String className) {
  108. final String regex =
  109. "(?m)^ *[0-9]+: +([0-9]+) +[0-9]+ +\\Q"+className+"\\E$";
  110. final Callable<Integer> objectsInUse =
  111. new Callable<Integer>() { public Integer call() {
  112. Integer i = Integer.parseInt(
  113. match(commandOutputOf(jmap, "-histo:live", childPid),
  114. regex, 1));
  115. if (i > 100)
  116. System.out.print(
  117. commandOutputOf(jmap,
  118. "-dump:file=dump,format=b",
  119. childPid));
  120. return i;
  121. }};
  122. try { return rendezvousParent(child, objectsInUse); }
  123. catch (Throwable t) { unexpected(t); return -1; }
  124. }
  125. static void realMain(String[] args) throws Throwable {
  126. // jmap doesn't work on Windows
  127. if (System.getProperty("os.name").startsWith("Windows"))
  128. return;
  129. final String childClassName = Job.class.getName();
  130. final String classToCheckForLeaks = Job.classToCheckForLeaks();
  131. final String uniqueID =
  132. String.valueOf(new Random().nextInt(Integer.MAX_VALUE));
  133. final String[] jobCmd = {
  134. java, "-Xmx8m", "-XX:+UsePerfData",
  135. "-classpath", System.getProperty("test.classes", "."),
  136. childClassName, uniqueID
  137. };
  138. final Process p = new ProcessBuilder(jobCmd).start();
  139. final String childPid =
  140. match(commandOutputOf(jps, "-m"),
  141. "(?m)^ *([0-9]+) +\\Q"+childClassName+"\\E *"+uniqueID+"$", 1);
  142. final int n0 = objectsInUse(p, childPid, classToCheckForLeaks);
  143. final int n1 = objectsInUse(p, childPid, classToCheckForLeaks);
  144. equal(p.waitFor(), 0);
  145. equal(p.exitValue(), 0);
  146. failed += p.exitValue();
  147. // Check that no objects were leaked.
  148. System.out.printf("%d -> %d%n", n0, n1);
  149. check(Math.abs(n1 - n0) < 2); // Almost always n0 == n1
  150. check(n1 < 20);
  151. drainers.shutdown();
  152. }
  153. //----------------------------------------------------------------
  154. // The main class of the child process.
  155. // Job's job is to:
  156. // - provide the name of a class to check for leaks.
  157. // - call rendezvousChild exactly twice, while quiescent.
  158. // - in between calls to rendezvousChild, run code that may leak.
  159. //----------------------------------------------------------------
  160. public static class Job {
  161. static String classToCheckForLeaks() {
  162. return
  163. "java.util.concurrent.locks.AbstractQueuedSynchronizer$Node";
  164. }
  165. public static void main(String[] args) throws Throwable {
  166. final ReentrantLock lock = new ReentrantLock();
  167. lock.lock();
  168. final ReentrantReadWriteLock rwlock
  169. = new ReentrantReadWriteLock();
  170. final ReentrantReadWriteLock.ReadLock readLock
  171. = rwlock.readLock();
  172. final ReentrantReadWriteLock.WriteLock writeLock
  173. = rwlock.writeLock();
  174. rwlock.writeLock().lock();
  175. final BlockingQueue<Object> q = new LinkedBlockingQueue<Object>();
  176. final Semaphore fairSem = new Semaphore(0, true);
  177. final Semaphore unfairSem = new Semaphore(0, false);
  178. //final int threads =
  179. //rnd.nextInt(Runtime.getRuntime().availableProcessors() + 1) + 1;
  180. final int threads = 3;
  181. // On Linux, this test runs very slowly for some reason,
  182. // so use a smaller number of iterations.
  183. // Solaris can handle 1 << 18.
  184. // On the other hand, jmap is much slower on Solaris...
  185. final int iterations = 1 << 8;
  186. final CyclicBarrier cb = new CyclicBarrier(threads+1);
  187. for (int i = 0; i < threads; i++)
  188. new Thread() { public void run() {
  189. try {
  190. final Random rnd = new Random();
  191. for (int j = 0; j < iterations; j++) {
  192. if (j == iterations/10 || j == iterations - 1) {
  193. cb.await(); // Quiesce
  194. cb.await(); // Resume
  195. }
  196. //int t = rnd.nextInt(2000);
  197. int t = rnd.nextInt(900);
  198. check(! lock.tryLock(t, NANOSECONDS));
  199. check(! readLock.tryLock(t, NANOSECONDS));
  200. check(! writeLock.tryLock(t, NANOSECONDS));
  201. equal(null, q.poll(t, NANOSECONDS));
  202. check(! fairSem.tryAcquire(t, NANOSECONDS));
  203. check(! unfairSem.tryAcquire(t, NANOSECONDS));
  204. }
  205. } catch (Throwable t) { unexpected(t); }
  206. }}.start();
  207. cb.await(); // Quiesce
  208. rendezvousChild(); // Measure
  209. cb.await(); // Resume
  210. cb.await(); // Quiesce
  211. rendezvousChild(); // Measure
  212. cb.await(); // Resume
  213. System.exit(failed);
  214. }
  215. // If something goes wrong, we might never see it, since IO
  216. // streams are connected to the parent. So we need a special
  217. // purpose print method to debug Jobs.
  218. static void debugPrintf(String format, Object... args) {
  219. try {
  220. new PrintStream(new FileOutputStream("/dev/tty"))
  221. .printf(format, args);
  222. } catch (Throwable t) { throw new Error(t); }
  223. }
  224. }
  225. //--------------------- Infrastructure ---------------------------
  226. static volatile int passed = 0, failed = 0;
  227. static void pass() {passed++;}
  228. static void fail() {failed++; Thread.dumpStack();}
  229. static void fail(String msg) {System.out.println(msg); fail();}
  230. static void unexpected(Throwable t) {failed++; t.printStackTrace();}
  231. static void check(boolean cond) {if (cond) pass(); else fail();}
  232. static void check(boolean cond, String m) {if (cond) pass(); else fail(m);}
  233. static void equal(Object x, Object y) {
  234. if (x == null ? y == null : x.equals(y)) pass();
  235. else fail(x + " not equal to " + y);}
  236. public static void main(String[] args) throws Throwable {
  237. try {realMain(args);} catch (Throwable t) {unexpected(t);}
  238. System.out.printf("%nPassed = %d, failed = %d%n%n", passed, failed);
  239. if (failed > 0) throw new AssertionError("Some tests failed");}
  240. }