当前位置: 首页>>代码示例>>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;未经允许,请勿转载。