9

Pls help me to understand how can we make a thread to sleep for a infinite time period .

Logesh
  • 151
  • 1
  • 1
  • 4
  • 12
    Why would you want that? – KaareZ Jun 15 '15 at 12:46
  • 3
    `Thread.sleep(Long.MAX_VALUE); ` is not infinite but still long enough that you won't see the end of it... – assylias Jun 15 '15 at 12:48
  • 2
    Use an infinite loop but, why do you need that? For what purpose? – Francisco Romero Jun 15 '15 at 12:48
  • 1
    That's a recipe for disaster - yeah @assylias has given you something near to infinity. – ring bearer Jun 15 '15 at 12:49
  • Why to initiate such a thread? Please enlighten us, a bit more about what is actually the real scenario !!!! – nIcE cOw Jun 15 '15 at 12:50
  • 1
    The core question: WHY? – Andremoniy Jun 15 '15 at 12:52
  • 4
    You're asking the wrong question. This is an XY problem. The right question is probably something more like "How do I make one thread wait for another thread to finish?" or something like that. – nhgrif Jun 15 '15 at 12:54
  • Sure a lot of people asking for use cases. How about this one: If the thread continues past a certain point, the application dies. – Jeffrey Aguilera Dec 06 '18 at 20:20
  • Just one example why one may need such infinite sleep: I'm testing that some operation may be executed concurrently (without lock). So I need to block one thread in the middle and check that another thread has finished successfully. – Ilya Serbis May 24 '19 at 17:35
  • @KaareZ I have to work with a poor Java implementation that terminates as soon as the main thread dies. Therefore, I'd like to have the main thread stay alive indefinitely, or better yet completely yield its execution time to other threads. The codebase is needs to work on this poor implementation as well as plenty of other valid implementations and it is infeasible to rewrite the program so that the main thread takes over and does the work in this case. Now do you actually have any *useful* suggestions for an issue like this??? – Kröw Dec 17 '22 at 19:55

7 Answers7

31

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) {
    Thread.sleep(Long.MAX_VALUE);
}
Liviu Stirb
  • 5,876
  • 3
  • 35
  • 40
  • 36
    This implementation will wake up after 292 billion years before sleeping again, I wouldn't use this in production since 292 billion years is much less than infinity. Imagine the kind of support that my successor will need to provide by then. – Ibrahim Arief Jun 15 '15 at 12:59
  • 2
    @IbrahimArief Unless in 292 billion years true is not false, it will fall asleep again (if no Exception has occurred in the meantime ;-). – Würgspaß Jun 15 '15 at 13:05
  • 1
    What a hack: think about all the CPU time wasted for looping! – Rick77 Jul 21 '20 at 12:50
  • 2
    the loop never consume any signification CPU usage because it sleeps for 292 billion years – Blanket Fox Jun 28 '21 at 11:58
9

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) {
        obj.wait();
    }
 }

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.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
8
Thread.currentThread().join();

Will sleep until the JVM is killed.

Paul Roub
  • 36,322
  • 27
  • 84
  • 93
Taylor Gautier
  • 4,916
  • 7
  • 30
  • 24
  • Yes ... but it is possible that they might change the JVM so that this pathological case throws an exception. (Just saying). – Stephen C Aug 27 '18 at 10:46
0

Make it wait for a mutex or resource that will never be released. It's the deadlock principle. The better way is to make the thread to finish his code, so it will end and not be started again.

Edit: I don't recommand an infinite loop since it's the pooling principle. It will consume a lot of resources for nothing.

JFPicard
  • 5,029
  • 3
  • 19
  • 43
0

You can use class CyclicBarrier from the JDK.

new CyclicBarrier(2).await();

Constructor argument is the number of threads that must invoke await method before the barrier is reached.

k13i
  • 4,011
  • 3
  • 35
  • 63
-1

It's actually quite easy if you do it this way:

public static boolean timerController = false;
Timer timer = new Timer();
public TimerTask task = new TimerTask() {
    
    public void run() {
        if(timerController == false){
        tracker();
        t.setText("<html><br/>Day " + day + ", hour " + hour + "<br/>");
        System.out.println("Hour: " + hour + " Day: " + day + " Real time seconds " + realTime + " Seconds");}
    }
    
};

public void start() {

    timer.scheduleAtFixedRate(task, 1000, 1000);

}   

public void pause(){
timerController = true;
}

public void resume(){
timerController = false;
}

Make a timer object in another class, and simply start, pause, and resume with the three methods. It should "stop" when you pause the timer, and you won't need to deal with any exception handling or any try/catch statements!

-1

Just make an infinite loop

while(true){}
Sathesh
  • 6,323
  • 6
  • 36
  • 48