Path: blob/master/test/jdk/java/nio/channels/Selector/SelectorUtils.java
41153 views
/*1* Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*/2223import java.lang.management.ManagementFactory;24import java.lang.management.MonitorInfo;25import java.lang.management.ThreadInfo;26import java.nio.channels.Selector;2728public class SelectorUtils {2930/**31* tell if the monitor of an Object is held by a Thread.32* @param t the Thread to hold the monitor of the selected-key set33* @param lock the Object34* @return35*/36public static boolean mightHoldLock(Thread t, Object lock) {37long tid = t.getId();38int hash = System.identityHashCode(lock);39ThreadInfo ti = ManagementFactory.getThreadMXBean().40getThreadInfo(new long[]{ tid} , true, false, 100)[0];41if (ti != null) {42for (MonitorInfo mi : ti.getLockedMonitors()) {43if (mi.getIdentityHashCode() == hash)44return true;45}46}47return false;48}4950/**51* Spin until the monitor of the selected-key set is likely held52* as selected operations are specified to synchronize on the53* selected-key set.54* @param t the Thread to hold the monitor of the selected-key set55* @param sel the Selector56* @throws Exception57*/58public static void spinUntilLocked(Thread t, Selector sel) throws Exception {59while (!mightHoldLock(t, sel.selectedKeys())) {60Thread.sleep(50);61}62}63}646566