當前位置: 首頁>>代碼示例>>Java>>正文


Java VirtualMachine.attach方法代碼示例

本文整理匯總了Java中com.sun.tools.attach.VirtualMachine.attach方法的典型用法代碼示例。如果您正苦於以下問題:Java VirtualMachine.attach方法的具體用法?Java VirtualMachine.attach怎麽用?Java VirtualMachine.attach使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在com.sun.tools.attach.VirtualMachine的用法示例。


在下文中一共展示了VirtualMachine.attach方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: main

import com.sun.tools.attach.VirtualMachine; //導入方法依賴的package包/類
public static void main(String[] args) throws Exception {

        String value = System.getProperty("jdk.attach.allowAttachSelf");
        boolean canAttachSelf = (value != null) && !value.equals("false");

        String vmid = "" + ProcessHandle.current().pid();

        VirtualMachine vm = null;
        try {
            vm = VirtualMachine.attach(vmid);
            if (!canAttachSelf)
                throw new RuntimeException("Attached to self not expected");
        } catch (IOException ioe) {
            if (canAttachSelf)
                throw ioe;
        } finally {
            if (vm != null) vm.detach();
        }

    }
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:21,代碼來源:AttachSelf.java

示例2: main

import com.sun.tools.attach.VirtualMachine; //導入方法依賴的package包/類
public static void main(String[] args) throws Exception {
    System.out.println("#modules loaded: " + moduleInfoCont());

    String vmid = "" + ProcessHandle.current().pid();
    VirtualMachine vm = VirtualMachine.attach(vmid);

    for (String test : args) {
        switch (test) {
            case "jmx" :
                startJMXAgent(vm);
                break;
            case "javaagent" :
                startJavaAgent(vm, createAgentJar());
                break;
        }

        System.out.println("#modules loaded: " + moduleInfoCont());
    }
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:20,代碼來源:Main.java

示例3: attach

import com.sun.tools.attach.VirtualMachine; //導入方法依賴的package包/類
private static VirtualMachine attach(String pid) {
    try {
        return VirtualMachine.attach(pid);
    } catch (Exception x) {
        String msg = x.getMessage();
        if (msg != null) {
            System.err.println(pid + ": " + msg);
        } else {
            x.printStackTrace();
        }
        if ((x instanceof AttachNotSupportedException) && haveSA()) {
            System.err.println("The -F option can be used when the " +
              "target process is not responding");
        }
        System.exit(1);
        return null; // keep compiler happy
    }
}
 
開發者ID:SunburstApps,項目名稱:OpenJSharp,代碼行數:19,代碼來源:JMap.java

示例4: attachAgent

import com.sun.tools.attach.VirtualMachine; //導入方法依賴的package包/類
static void attachAgent(File agentFile, Class<?>[] transformers) {
    try {
        String pid = ManagementFactory.getRuntimeMXBean().getName();
        VirtualMachine vm = VirtualMachine.attach(pid.substring(0, pid.indexOf('@')));
        vm.loadAgent(agentFile.getAbsolutePath());
        vm.detach();

        Agent.getInstance().process(transformers);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
開發者ID:Yamakaja,項目名稱:RuntimeTransformer,代碼行數:13,代碼來源:TransformerUtils.java

示例5: getVirtualMachine

import com.sun.tools.attach.VirtualMachine; //導入方法依賴的package包/類
/**
 * 獲取當前JVM
 * @return
 * @throws IOException 
 * @throws AttachNotSupportedException 
 */
public static VirtualMachine getVirtualMachine() throws AttachNotSupportedException, IOException
{
	String pid = ManagementFactory.getRuntimeMXBean().getName();
	int indexOf = pid.indexOf('@');
	if (indexOf > 0) {
		pid = pid.substring(0, indexOf);
	}
	return VirtualMachine.attach(pid);
}
 
開發者ID:juebanlin,項目名稱:util4j,代碼行數:16,代碼來源:JvmUtil.java

示例6: testGetFlag

import com.sun.tools.attach.VirtualMachine; //導入方法依賴的package包/類
public static void testGetFlag(String flagName, String flagValue) throws Exception {
  ProcessBuilder pb = runTarget(flagName, flagValue);

  Process target = pb.start();

  try {
    waitForReady(target);

    int pid = (int)target.pid();

    HotSpotVirtualMachine vm = (HotSpotVirtualMachine)VirtualMachine.attach(((Integer)pid).toString());

    // Test Get
    BufferedReader remoteDataReader = new BufferedReader(new InputStreamReader(
        vm.printFlag(flagName)));

    boolean foundExpectedLine = false;

    String line = null;
    while((line = remoteDataReader.readLine()) != null) {
      System.out.println("printFlag: " + line);
      if (line.equals("-XX:" + flagName + "=" + flagValue)) {
        foundExpectedLine = true;
      }
    }

    Asserts.assertTrue(foundExpectedLine, "Didn't get the expected output: '-XX:" + flagName + "=" + flagValue + "'");

    vm.detach();
  }
  finally {
    target.destroy();
    target.waitFor();
  }
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:36,代碼來源:AttachSetGetFlag.java

示例7: main

import com.sun.tools.attach.VirtualMachine; //導入方法依賴的package包/類
public static void main(String[] args) throws Exception {
    String pid = args[0]; // pid as a string
    System.out.println("Starting TestManager for PID = " + pid);
    System.out.flush();
    VirtualMachine vm = VirtualMachine.attach(pid);

    String agentPropLocalConnectorAddress = (String)
        vm.getAgentProperties().get(LOCAL_CONNECTOR_ADDRESS_PROP);

    int vmid = Integer.parseInt(pid);
    String jvmstatLocalConnectorAddress =
        ConnectorAddressLink.importFrom(vmid);

    if (agentPropLocalConnectorAddress == null &&
        jvmstatLocalConnectorAddress == null) {
        // No JMX Connector address so attach to VM, and start local agent
        startManagementAgent(pid);
        agentPropLocalConnectorAddress = (String)
            vm.getAgentProperties().get(LOCAL_CONNECTOR_ADDRESS_PROP);
        jvmstatLocalConnectorAddress =
            ConnectorAddressLink.importFrom(vmid);
    }


    // Test address obtained from agent properties
    System.out.println("Testing the connector address from agent properties");
    connect(pid, agentPropLocalConnectorAddress);

    // Test address obtained from jvmstat buffer
    System.out.println("Testing the connector address from jvmstat buffer");
    connect(pid, jvmstatLocalConnectorAddress);

    // Shutdown application
    int port = Integer.parseInt(args[1]);
    System.out.println("Shutdown process via TCP port: " + port);
    Socket s = new Socket();
    s.connect(new InetSocketAddress(port));
    s.close();
}
 
開發者ID:lambdalab-mirror,項目名稱:jdk8u-jdk,代碼行數:40,代碼來源:TestManager.java

示例8: getInstanceCountFromHeapHisto

import com.sun.tools.attach.VirtualMachine; //導入方法依賴的package包/類
/**
 * 'vm.heapHisto("-live")' will request a full GC
 */
private static int getInstanceCountFromHeapHisto() throws AttachNotSupportedException, Exception {
    int instanceCount = 0;

    HotSpotVirtualMachine vm = (HotSpotVirtualMachine) VirtualMachine
            .attach(Long.toString(ProcessTools.getProcessId()));
    try {
        try (InputStream heapHistoStream = vm.heapHisto("-live");
                BufferedReader in = new BufferedReader(new InputStreamReader(heapHistoStream))) {
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                if (inputLine.contains(TARGET_CLASS)) {
                    instanceCount = Integer.parseInt(inputLine
                            .split("[ ]+")[2]);
                    System.out.println("instance count: " + instanceCount);
                    break;
                }
            }
        }
    } finally {
        vm.detach();
    }

    assertGreaterThan(instanceCount, 0, "No instances of " + TARGET_CLASS + " are found");

    return instanceCount;
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:30,代碼來源:TestLoggerWeakRefLeak.java

示例9: runTest

import com.sun.tools.attach.VirtualMachine; //導入方法依賴的package包/類
public static boolean runTest() throws Exception {
  ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(
    "-XX:+UnlockDiagnosticVMOptions", "-XX:+PauseAtStartup", "AttachWithStalePidFileTarget");
  Process target = pb.start();
  Path pidFile = null;

  try {
    int pid = getUnixProcessId(target);

    // create the stale .java_pid file. use hard-coded /tmp path as in th VM
    pidFile = createJavaPidFile(pid);
    if(pidFile == null) {
      return false;
    }

    // wait for vm.paused file to be created and delete it once we find it.
    waitForAndResumeVM(pid);

    waitForTargetReady(target);

    HotSpotVirtualMachine vm = (HotSpotVirtualMachine)VirtualMachine.attach(((Integer)pid).toString());
    BufferedReader remoteDataReader = new BufferedReader(new InputStreamReader(vm.remoteDataDump()));
    String line = null;
    while((line = remoteDataReader.readLine()) != null);

    vm.detach();
    return true;
  }
  finally {
    target.destroy();
    target.waitFor();

    if(pidFile != null && Files.exists(pidFile)) {
      Files.delete(pidFile);
    }
  }
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:38,代碼來源:AttachWithStalePidFile.java

示例10: executeCommandForPid

import com.sun.tools.attach.VirtualMachine; //導入方法依賴的package包/類
private static void executeCommandForPid(String pid, String command)
    throws AttachNotSupportedException, IOException,
           UnsupportedEncodingException {
    VirtualMachine vm = VirtualMachine.attach(pid);

    // Cast to HotSpotVirtualMachine as this is an
    // implementation specific method.
    HotSpotVirtualMachine hvm = (HotSpotVirtualMachine) vm;
    String lines[] = command.split("\\n");
    for (String line : lines) {
        if (line.trim().equals("stop")) {
            break;
        }
        try (InputStream in = hvm.executeJCmd(line);) {
            // read to EOF and just print output
            byte b[] = new byte[256];
            int n;
            boolean messagePrinted = false;
            do {
                n = in.read(b);
                if (n > 0) {
                    String s = new String(b, 0, n, "UTF-8");
                    System.out.print(s);
                    messagePrinted = true;
                }
            } while (n > 0);
            if (!messagePrinted) {
                System.out.println("Command executed successfully");
            }
        }
    }
    vm.detach();
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:34,代碼來源:JCmd.java

示例11: main

import com.sun.tools.attach.VirtualMachine; //導入方法依賴的package包/類
public static void main(String[] args) throws Exception {

    if (args.length < 2 || args.length > 3) {
      System.err.println("Usage: java -cp dir/agent.jar:/.../jvm/java-8-jdk/lib/tools.jar " +
          "io.prometheus.jmx.shaded.io.prometheus.jmx.Attach pid [host:]<port>:<yaml configuration file>");
      System.exit(1);
    }


    List<VirtualMachineDescriptor> vms = VirtualMachine.list();
    VirtualMachineDescriptor selectedVM = null;
    for (VirtualMachineDescriptor vmd : vms) {
      if (vmd.id().equals(args[0])) {
        selectedVM = vmd;
      }
    }

    if (selectedVM == null) {
      System.err.println("No such java process with pid=" + args[0]);
      System.exit(-1);
    }

    VirtualMachine attachedVm = VirtualMachine.attach(selectedVM);
    File currentJarFile = new File(Attach.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath());

    attachedVm.loadAgent(currentJarFile.getAbsolutePath(), args[1]);
    attachedVm.detach();

  }
 
開發者ID:flokkr,項目名稱:jmxpromo,代碼行數:30,代碼來源:Attach.java

示例12: runTest

import com.sun.tools.attach.VirtualMachine; //導入方法依賴的package包/類
public static boolean runTest() throws Exception {
  ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(
    "-XX:+UnlockDiagnosticVMOptions", "-XX:+PauseAtStartup", "AttachWithStalePidFileTarget");
  Process target = pb.start();
  Path pidFile = null;

  try {
    int pid = getUnixProcessId(target);

    // create the stale .java_pid file. use hard-coded /tmp path as in th VM
    pidFile = createJavaPidFile(pid);
    if(pidFile == null) {
      return false;
    }

    // wait for vm.paused file to be created and delete it once we find it.
    waitForAndResumeVM(pid);

    // unfortunately there's no reliable way to know the VM is ready to receive the
    // attach request so we have to do an arbitrary sleep.
    Thread.sleep(5000);

    HotSpotVirtualMachine vm = (HotSpotVirtualMachine)VirtualMachine.attach(((Integer)pid).toString());
    BufferedReader remoteDataReader = new BufferedReader(new InputStreamReader(vm.remoteDataDump()));
    String line = null;
    while((line = remoteDataReader.readLine()) != null);

    vm.detach();
    return true;
  }
  finally {
    target.destroy();
    target.waitFor();

    if(pidFile != null && Files.exists(pidFile)) {
      Files.delete(pidFile);
    }
  }
}
 
開發者ID:arodchen,項目名稱:MaxSim,代碼行數:40,代碼來源:AttachWithStalePidFile.java

示例13: runTests

import com.sun.tools.attach.VirtualMachine; //導入方法依賴的package包/類
public static void runTests(int pid) throws Exception {
    VirtualMachine vm = VirtualMachine.attach(""+pid);
    try {

        basicTests(vm);

        testLocalAgent(vm);

        // we retry the remote case several times in case the error
        // was caused by a port conflict
        int i = 0;
        boolean success = false;
        do {
            try {
                System.err.println("Trying remote agent. Try #" + i);
                testRemoteAgent(vm);
                success = true;
            } catch(Exception ex) {
                System.err.println("testRemoteAgent failed with exception:");
                ex.printStackTrace();
                System.err.println("Retrying.");
            }
            i++;
        } while(!success && i < MAX_RETRIES);
        if (!success) {
            throw new Exception("testRemoteAgent failed after " + MAX_RETRIES + " tries");
        }
    } finally {
        vm.detach();
    }
}
 
開發者ID:lambdalab-mirror,項目名稱:jdk8u-jdk,代碼行數:32,代碼來源:StartManagementAgent.java

示例14: runThreadDump

import com.sun.tools.attach.VirtualMachine; //導入方法依賴的package包/類
private static void runThreadDump(String pid, String args[]) throws Exception {
    VirtualMachine vm = null;
    try {
        vm = VirtualMachine.attach(pid);
    } catch (Exception x) {
        String msg = x.getMessage();
        if (msg != null) {
            System.err.println(pid + ": " + msg);
        } else {
            x.printStackTrace();
        }
        if ((x instanceof AttachNotSupportedException) &&
            (loadSAClass() != null)) {
            System.err.println("The -F option can be used when the target " +
                "process is not responding");
        }
        System.exit(1);
    }

    // Cast to HotSpotVirtualMachine as this is implementation specific
    // method.
    InputStream in = ((HotSpotVirtualMachine)vm).remoteDataDump((Object[])args);

    // read to EOF and just print output
    byte b[] = new byte[256];
    int n;
    do {
        n = in.read(b);
        if (n > 0) {
            String s = new String(b, 0, n, "UTF-8");
            System.out.print(s);
        }
    } while (n > 0);
    in.close();
    vm.detach();
}
 
開發者ID:lambdalab-mirror,項目名稱:jdk8u-jdk,代碼行數:37,代碼來源:JStack.java

示例15: loadInstrumentationAgent

import com.sun.tools.attach.VirtualMachine; //導入方法依賴的package包/類
private static void loadInstrumentationAgent(String myName, byte[] buf) throws Exception {
    // Create agent jar file on the fly
    Manifest m = new Manifest();
    m.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
    m.getMainAttributes().put(new Attributes.Name("Agent-Class"), myName);
    m.getMainAttributes().put(new Attributes.Name("Can-Redefine-Classes"), "true");
    File jarFile = File.createTempFile("agent", ".jar");
    jarFile.deleteOnExit();
    JarOutputStream jar = new JarOutputStream(new FileOutputStream(jarFile), m);
    jar.putNextEntry(new JarEntry(myName.replace('.', '/') + ".class"));
    jar.write(buf);
    jar.close();
    String pid = Long.toString(ProcessTools.getProcessId());
    System.out.println("Our pid is = " + pid);
    VirtualMachine vm = VirtualMachine.attach(pid);
    vm.loadAgent(jarFile.getAbsolutePath());
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:18,代碼來源:DefineClass.java


注:本文中的com.sun.tools.attach.VirtualMachine.attach方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。