How can we make a thread to sleep for a infinite time in java?

I can't think of a good reason for doing this. As one of the comments noted Long.MAX_VALUE is roughly 292 billion years so probably Thread.sleep(Long.MAX_VALUE) is enough. But if you want a theoretical infinite sleep solution:

while (true) {

Literally, you can't. No Java application can run for an infinite amount of time. The hardware will die first :-)

But in practice1, the following will sleep until the JVM terminates ... or the thread is interrupted.

 public void freeze() throws InterruptedException {
    Object obj = new Object();
    synchronized (obj) {

If you wanted to you could catch the exception within a while (true) loop. And doing the same with "sleep(max int)" is equivalent.

But frankly, making a thread go to sleep "for ever" is wasteful2, and probably a bad idea. I have no doubt that there will be better ways to achieve what you are really trying to do.

1 - These solutions I talk about are for when a thread needs to make itself go to sleep. If you one thread to unilaterally make a different thread go to sleep, it can't do that safely. You could use the deprecated Thread.suspend() method, but it is dangerous, and it may not be available on future Java platforms.

2 - A thread stack occupies a significant amount of memory, and it cannot be released until the thread terminates.


Will sleep until the JVM is killed.