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

6

9

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

Reinaldo answered 15/6, 2015 at 12:45 Comment(10)
Why would you want that?Jacquard
Thread.sleep(Long.MAX_VALUE); is not infinite but still long enough that you won't see the end of it...Oloughlin
Use an infinite loop but, why do you need that? For what purpose?Austria
That's a recipe for disaster - yeah @Oloughlin has given you something near to infinity.Ambary
Why to initiate such a thread? Please enlighten us, a bit more about what is actually the real scenario !!!!Cameroun
The core question: WHY?Weatherproof
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.Crankle
Sure a lot of people asking for use cases. How about this one: If the thread continues past a certain point, the application dies.Nexus
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.Philps
@Jacquard 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???Spickandspan
O
32

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);
}
Oneiric answered 15/6, 2015 at 12:48 Comment(4)
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.Collotype
@IbrahimArief Unless in 292 billion years true is not false, it will fall asleep again (if no Exception has occurred in the meantime ;-).Chummy
What a hack: think about all the CPU time wasted for looping!Postdoctoral
the loop never consume any signification CPU usage because it sleeps for 292 billion yearsCanalize
G
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.

Greaser answered 15/6, 2015 at 12:56 Comment(0)
K
9
Thread.currentThread().join();

Will sleep until the JVM is killed.

Keithakeithley answered 26/4, 2018 at 20:59 Comment(1)
Yes ... but it is possible that they might change the JVM so that this pathological case throws an exception. (Just saying).Greaser
C
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.

Cripps answered 15/6, 2015 at 12:49 Comment(3)
new Semaphore(0).acquire();Quaint
Pooling is not bad if we will sleep the Thread for a long time.Mutate
I agree, but a pooling like while(true) {} or for(;;) {} is really bad.Cripps
K
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.

Kinfolk answered 23/7, 2019 at 9:17 Comment(0)
H
-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!

Hump answered 11/11, 2022 at 18:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.