Suspending the JVM for a limited amount of time

橙三吉。 提交于 2020-05-29 08:32:10

问题


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.


回答1:


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.




回答2:


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?




回答3:


Use a Virtual Machine and suspend its execution outright.




回答4:


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.



来源:https://stackoverflow.com/questions/2674292/suspending-the-jvm-for-a-limited-amount-of-time

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!