List of usage examples for java.lang Thread getDefaultUncaughtExceptionHandler
public static UncaughtExceptionHandler getDefaultUncaughtExceptionHandler()
From source file:org.neo4j.io.pagecache.PageCacheTest.java
@Test(timeout = SEMI_LONG_TIMEOUT_MILLIS) public void backgroundThreadsMustGracefullyShutDown() throws Exception { assumeTrue("For some reason, this test is very flaky on Windows", !SystemUtils.IS_OS_WINDOWS); int iterations = 1000; List<WeakReference<PageCache>> refs = new LinkedList<>(); final Queue<Throwable> caughtExceptions = new ConcurrentLinkedQueue<>(); final Thread.UncaughtExceptionHandler exceptionHandler = (t, e) -> { e.printStackTrace();/*from w ww . j a va 2 s . co m*/ caughtExceptions.offer(e); }; Thread.UncaughtExceptionHandler defaultUncaughtExceptionHandler = Thread .getDefaultUncaughtExceptionHandler(); Thread.setDefaultUncaughtExceptionHandler(exceptionHandler); try { generateFileWithRecords(file("a"), recordCount, recordSize); int filePagesInTotal = recordCount / recordsPerFilePage; for (int i = 0; i < iterations; i++) { PageCache cache = createPageCache(fs, maxPages, pageCachePageSize, PageCacheTracer.NULL); // Touch all the pages PagedFile pagedFile = cache.map(file("a"), filePageSize); try (PageCursor cursor = pagedFile.io(0, PF_SHARED_READ_LOCK)) { for (int j = 0; j < filePagesInTotal; j++) { assertTrue(cursor.next()); } } // We're now likely racing with the eviction thread pagedFile.close(); cache.close(); refs.add(new WeakReference<>(cache)); assertTrue(caughtExceptions.isEmpty()); } } finally { Thread.setDefaultUncaughtExceptionHandler(defaultUncaughtExceptionHandler); } // Once the page caches has been closed and all references presumably set to null, then the only thing that // could possibly strongly reference the cache is any lingering background thread. If we do a couple of // GCs, then we should observe that the WeakReference has been cleared by the garbage collector. If it // hasn't, then something must be keeping it alive, even though it has been closed. int maxChecks = 100; boolean passed; do { System.gc(); Thread.sleep(100); passed = true; for (WeakReference<PageCache> ref : refs) { if (ref.get() != null) { passed = false; } } } while (!passed && maxChecks-- > 0); if (!passed) { List<PageCache> nonNullPageCaches = new LinkedList<>(); for (WeakReference<PageCache> ref : refs) { PageCache pageCache = ref.get(); if (pageCache != null) { nonNullPageCaches.add(pageCache); } } if (!nonNullPageCaches.isEmpty()) { fail("PageCaches should not be held live after close: " + nonNullPageCaches); } } }