title: How to generate a cpu snapshot in production?
body: <p>With VisualVM, I can attach to a local java process, start/stop CPU profiling, and generate a snapshot. I don't even need to instrument the process with any special agents etc.</p>
  
  <p>Is it possible to do the same thing on a headless production server? I know I can configure the process to attach the debugger remotely, but I want to minimize the amount and impact of changing the customer environment. I just want to run a command to profile for a while and generate a snapshot file, which I can scp to my workstation for analysis with VisualVM or equivalent.</p>
  
  <p>Preferably, the whatever program I run to do this should be freely redistributable, so that I can bundle it with my Java app and have it be available in the customer environment.</p>
  
  <p>Ideally, just like with VisualVM, I'd like to be able to attach to a running system without a restart.</p>
  
  <p>The closest I've found so far is instrumenting with <a href="http://docs.oracle.com/javase/7/docs/technotes/samples/hprof.html" rel="noreferrer">hprof</a>:</p>
  
  <pre><code>  java -agentlib:hprof=cpu=samples,interval=20,depth=3 classname
  </code></pre>
  
  <p>but that requires a restart to start profiling and another to stop, as I don't see a way to turn sampling on and off at runtime.</p>
  
  <p>Is there a better way? If there's no out-of-the-box solution, how would one build it? It must be possible since VisualVM does it.</p>