4

How can I suspend the execution of a JVM for a configurable amount of time, similar to want happens on a full, serial, Garbage Collection? I want to test some edge cases but it's difficult to create the exact pauses I need with manually generating garbage + System.gc().


I'm trying to 'freeze' all the threads in the application, to simulate a situation where an application becomes unresponsive, and then resumes execution. The application is part of a cluster, and I'm trying to debug some leave / join / re-join problems.

Robert Munteanu
  • 67,031
  • 36
  • 206
  • 278

4 Answers4

4

JVM suspend can be done from command line with jdb:

jdb -attach 8787
Initializing jdb ...
> suspend
All threads suspended.
> resume
All threads resumed.
> exit

But this requires it to be started with -Xdebug ...

There is also universal way to suspend and resume any process on Linux/Unix:

kill -SIGSTOP PID
kill -SIGCONT PID

See also How to suspend/resume a process in Windows?

Vadzim
  • 24,954
  • 11
  • 143
  • 151
3

When debugging from Eclipse you can supsend all threads, I guess other debuggers allow to do that too. So you'd need to start your server with JVM debug options and remote connect to it.

In my case (running JBoss) I modify the startup script by adding this line:

set JAVA_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,address=8787,server=y,suspend=n %JAVA_OPTS%

Then in Eclipse, Run -> Debug Configurations -> Remove Java Application -> New

Normally you just need to provide the hostname and the port.

Guillaume
  • 14,306
  • 3
  • 43
  • 40
2

Use a Virtual Machine and suspend its execution outright.

Robert Munteanu
  • 67,031
  • 36
  • 206
  • 278
1

I think you probably want something that is less invasive, but one approach is to have a controlling thread obtain a lock and then have all the other threads also try to obtain that lock. Then have the controlling thread sleep for the time you need before giving it up. A slightly less clumsy version of this would be to use a semaphore with one permit per thread and then have the controlling thread obtain them all, before having all the other threads try to acquire a permit.

As I said that's pretty invasive you'd have to hack that into your code for each thread.

Another approach would be to run your code under a debugger and manually suspend each thread.

Dean Povey
  • 9,256
  • 1
  • 41
  • 52
  • Thanks for you answer. I was looking for something which locks all threads, including some which are controlled by third party code. – Robert Munteanu Apr 20 '10 at 14:23
  • A slightly more involved approach might be to use the JPDA api to write your own debugger which enumerates the threads and suspends them. – Dean Povey Apr 20 '10 at 14:53
  • Sounds interesting. I did not find anything related to this in jdb. Do you have any pointers on how that can be done? – Robert Munteanu Apr 20 '10 at 15:05