How do you hang a thread in Java in one line? - java

By one line I mean at most 100 chars per line.
(I basically need this to keep the program alive. The main thread registers callback listeners that are run in separate threads. I just need the main one to hang forever and let the other threads do their work)

synchronized(this) {
while (true) {
this.wait();
}
}
(thanks to Carlos Heuberger. Exception handling omitted in the above code)
This will make the current thread wait on the monitor of the current class until someone calls notify(), or forever.

There are a few things you could do that would be better than hanging the initial thread forever:
Use otherThread.join(). This will cause the current thread you are running in to sleep until the other thread has finished executing.
As #nanda suggests, use ExcecutorService.shutdown() to wait until a pool of threads has finished.
Use otherThread.setDaemon(false) and simply let your initial thread exit. This will set your new threads as user threads. Java will not shut down until the only threads running are daemon threads.

Thread.sleep(Long.MAX_VALUE);
Ok, so it isn't forever, but talk about a really long time :)

Use executor. By using method shutdown() you'll force the executor to wait until all threads are finished.

With a CountDownLatch you can wait untill the count down reached 0, if you make sure it never counts down, maybe only when it needs to end. (This also result in 0% cpu, the opposite of loops that will run forever, and with join() your app will still finish when all other threads finished, The option of the executor is better, but will also end when all executed task have finished)

You can use thread.join to wait for all of the threads.

Here is a solution that is a one-liner, in that you only have to add one extra line. (You do have to add synchronized and throws InterruptedException to your main declaration though.) Also, it does not need access to, or even knowledge of the threads in the library you are using.
public static synchronized void main(String[] args) throws InterruptedException{
...
YourMainClass.class.wait(); // wait forever
}
It assumes you will never call notify on your main class and that you want to exit if you get an InterruptedException. (You can add a while (true) { ... } around the wait line if you really want to guard against that.)

public static void main(String[] args) {
Thread t = new Thread() {
#Override
public void run() {
try {
while (true) {
Thread.sleep(1000);
}
} catch (InterruptedException e) {
}
}
};
t.setDaemon(false);
t.start();
}

while(true) { Thread.sleep(1000); }

for(;;);
But it's very unlikely that hanging the thread is what you want. Instead, you should consider options like joining on the other threads.

Related

If java normal threads don't call "join", does it lead to unknown behavior before finish?

Normal java threads, not daemon threads, seem to execute till end, then main thread finishes, like this:
public static void main(String[] args) {
for(int i = 0; i < 3; ++i){
new Thread(new Runnable(){
#Override
public void run() {
try {
Thread.sleep(2000);
System.out.println("Does this still print?");
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
// Java normal threads don't have to call join, they'll still wait to finish.
System.out.println("Main thread start");
}
It will print:
Main thread start
i = 2
i = 0
i = 1
Does this still print?
Does this still print?
Does this still print?
What I saw here is, Java normal threads don't have to call join() and their holder still wait for them to finish. Not sure if my program is too simple to encounter any undefined behavior, could you kindly give some hints when should we use join()?
Thanks.
t.join() does not do anything to thread t in Java. All it does is not return until thread t has finished.
A Java program's main() thread does not wait for any other thread to finish after main() returns. It just ends, and any other non-daemon threads keep running.
Java is not like Go. In Go the program continues only as long as the main thread is alive, in Java any living nondaemon thread keeps the jvm around. In your code the main thread kicks off other threads and then dies. The new threads run to completion even though the main thread is long gone.
For "undefined behavior" I'm guessing you mean data races, or memory visibility issues, where you can't rely on one thing happening before another (for races) or on a value being visible across threads (for vidibility). Calling join does create a happens-before edge. So does calling println (since it acquires a lock). The Java language spec has a list of things that create a happens-before edge.
Calling get on a Future blocks until the future is done similar to how calling join on a Thread blocks until the thread is finished. If you use higher level constructs than just threads, whether it's executor services, CompletableFuture, reactive libraries, actor systems, or other concurrency models, then those are to different extents shielding you from the Thread api and you don't need join so much.

Java Wake Sleeping Thread

I did some reading of other post but didn't find an exact answer to what I'm looking for, so I hope someone can give some some clarification.
I have a program that will run for some time. I have some threads that run in the back ground that perform various tasks, to keep things simple let think of 3 threads. ThreadA performs a task every 10 seconds, where ThreadB does something every 30 seconds and ThreadC does something every 5 mintues.
I don't use busy waiting, and put the threads to sleep for the designated times.
My question is regarding a clean shut down. I have a variable that each of the threads have read access too, so they can see when the user initiates the exit of the program. The next time the threads are active, they exit their loops and join and all is good. But you can see that ThreadC only wakes up every 5 minutes.
The question I have is can I signal the sleeping threads to wake up and exit before their sleep time is over? If this is not possible, do I need to rework the code to use wait() and notify() or is there a better way?
Thread.sleep throws InterruptedException if the thread is interrupted during the sleep. Catch that, and check your flag.
If the threads are sleeping with Thread.sleep(...), you can wake them up with Thread.interrupt(). Make sure you're handling the InterruptedException and testing Thread.currentThread().isInterrupted() in your loops.
You can call the interrupt() method on your thread and will make your Thread go to running state from block state, but it will throw an exception which is InterruptedException which by then you can shutdown your thread in the catch block
Also other solution is that you can use the Timer Task that will call the run method on a certain time you specified without putting your Thread to the block state
example:
public class TimerBomb {
Toolkit toolkit;
Timer timer;
int count = 0;
public TimerBomb(int seconds) {
toolkit = Toolkit.getDefaultToolkit();
timer = new Timer();
timer.schedule(new RemindTask(), seconds * 1000, seconds*1000);
}
class RemindTask extends TimerTask {
public void run() {
//do stuff here
}
}
public static void main(String args[]) {
System.out.println("About to schedule task.");
Thread t = new Thread(new Runnable() {
#Override
public void run() {
new TimerBomb(5);
}
});
t.start();
System.out.println("Task scheduled.");
}
}
It will run every 5 second forever.
You should look into ExecutorService and its shutdownNow() method (which generally interrupts all the active threads). You sense reinventing the scheduling wheel.
All of the other answers are good answers to the question that you actually asked, but none of them gives the best answer to the question that you should have asked. The question is, what's the best way to schedule several periodic tasks that must recur with different periods? The answer is, use a java.util.concurrent.ScheduledExecutorService.
Like all ExeuctorServices, it provides methods, shutdown() and shutdownNow(), for when you want the tasks to stop.

Restarting a thread after it has been left

I have thread which contains a loop
while(isRunning){
}
isRunning is a Boolean variable with the value true, when some clicks on a button it gets false and so it leaves the loop and the run() function of the thread.
I want to create another button that on click it will reenter the run() function.
I am not sure if when I leave the run() function the thread dies or just stops.
I have tried using thread.run() but it didnt work.
Also I have looked for an answer in other's people questins about this matter but nothing seemed to help me. Thanks for the help
When a thread is finish processing it's code, There's no way of restarting it. You can either:
Create a new thread and pass the Runnable to that thread.
If you need to use that run() method often, use an Executor. You can use Executors.newSingleThreadExecutor(), which will supply you with a worker thread. (Reusable thread).
class Example {
static ExecutorService executor = Executors.newSingleThreadExecutor();
static Runnable run = new Runnable() {
public void run() {
}
};
public static void main(String[] args) {
//anytime you wanna run that code..
executor.execute(run);
}
}
If your thread runs to its end, it stops.
It will remain there for you to collect its return status until the thread is cleaned up.
To restart within the same thread, you need an extra control flow.
For instance:
while (restarted) {
while (isRunning) {
}
// Wait for a restart or end click
}
That is what so called worker threads in a thread pool do, which are intended for maximum performance.
But logically, you will probably simply want to create a new thread object and start that one.
new Thread(p).start();
Please read through java concurrency tutorial.
http://docs.oracle.com/javase/tutorial/essential/concurrency/
Just Maybe, guarded blocks might be useful for your case but your case is a little vague to recommend anything specific.
http://docs.oracle.com/javase/tutorial/essential/concurrency/guardmeth.html

Java: How to pause 1 class from running?

when I use Thread.sleep();, it pauses my entire program. Is there anything that pauses one class without using multithreading?
You don't pause classes, you pause threads. In the moment you pause your only thread, you pause you entire application as well. So there is no way to pause your only thread and expect the application will continue to run. You would need more than one thread if you expect your application do more than just waiting.
I think you're confusing some concepts here. Classes and Objects do not run. Threads run, and what they run are the instructions (code) defined by classes and objects.
So no, you cannot pause a Class or Object, only a Thread. Moreover, if your application is single threaded, then you only have a "main" thread, and if you pause that thread then your whole application will pause.
You can't pause a "class" per se. A class is just a "dead" container.
What you can do is pause a thread or a task.
Typically, you would create a separate thread to run the task you want to pause, and pause it when you like - because it runs in a separate thread, it will not hang you whole program.
See this simple example which you can run to better understand how threads can run in parallel:
public static void main(String[] args) throws InterruptedException {
Runnable lazyTask = new Runnable() {
#Override
public void run() {
System.out.println("Lazy: I feel like sleeping for a second");
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {}
System.out.println("Lazy: I feel better now");
}
};
new Thread(lazyTask).start();
//Let's wait a bit until the lazy task goes to sleep
Thread.sleep(100);
//now you can do something that will not hang
System.out.println("Main: I'm sleeping too, but only half a second");
Thread.sleep(500);
System.out.println("Main: And I can continue my job while that lazy task is still asleep");
}
No. You cannot. You have the main thread . Sleep will pause it. If you want stop run something without affect the main thread you need to fork it from the main thread , by use addiotnal thread

How does one stop a thread without a stop() method?

I have question about the Java threads. Here is my scenario:
I have a thread calling a method that could take while. The thread keeps itself on that method until I get the result. If I send another request to that method in the same way, now there are two threads running (provided the first did not return the result yet). But I want to give the priority to the last thread and don't want to get the results from the previously started threads. So how could I get rid of earlier threads when I do not have a stop method?
The standard design pattern is to use a local variable in the thread that can be set to stop it:
public class MyThread extends Thread {
private volatile boolean running = true;
public void stop() {
running = false;
}
public void run() {
while (running) {
// do your things
}
}
}
This way you can greacefully terminate the thread, i.e. without throwing an InterruptedException.
The best way really depends on what that method does. If it waits on something, chances are an interrupt will result in an InterruptedException which you handle and cleanly exit. If it's doing something busy, it won't:
class Scratchpad {
public static void main(String[] a) {
Thread t = new Thread(new Runnable() {
public void run() {doWork();}
});
t.start();
try {
Thread.sleep(50);
} catch (InterruptedException ie) {}
t.interrupt();
}
private static void doWork() {
for ( long i = 1; i != 0; i *=5 );
}
}
In the case above, the only viable solution really is a flag variable to break out of the loop early on a cancel, ala #inflagranti.
Another option for event-driven architectures is the poison-pill: if your method is waiting on a blocking queue for a new item, then you can have a global constant item called the "poison-pill" that when consumed (dequeued) you kill the thread:
try {
while(true) {
SomeType next = queue.take();
if ( next == POISON_PILL ) {
return;
}
consume(next);
}
} catch //...
EDIT:
It looks like what you really want is an executor service. When you submit a job to an executor service, you get back a Future which you can use to track results and cancel the job.
You can interrupt a Thread, its execution chain will throw an InterruptedException most of the time (see special cases in the documentation).
If you just want to slow down the other thread and not have it exit, you can take some other approach...
For one thing, just like exiting you can have a de-prioritize variable that, when set, puts your thread to sleep for 100ms on each iteration. This would effectively stop it while your other thread searched, then when you re-prioritize it it would go back to full speed.
However, this is a little sloppy. Since you only ever want one thing running but you want to have it remember to process others when the priority one is done, you may want to place your processing into a class with a .process() method that is called repeatedly. When you wish to suspend processing of that request you simply stop calling .process on that object for a while.
In this way you can implement a stack of such objects and your thread would just execute stack.peek().process(); every iteration, so pushing a new, more important task onto the stack would automatically stop any previous task from operating.
This leads to much more flexible scheduling--for instance you could have process() return false if there is nothing for it to do at which point your scheduler might go to the next item on the stack and try its' process() method, giving you some serious multi-tasking ability in a single thread without overtaxing your resources (network, I'm guessing)
There is a setPriority(int) method for Thread. You can set the first thread its priority like this:
Thread t = new Thread(yourRunnable);
t.start();
t.setPriority(Thread.MIN_PRIORITY); // The range goes from 1 to 10, I think
But this won't kill your thread. If you have only two threads using your runnable, then this is a good solution. But if you create threads in a loop and you always sets the priority of the last thread to minimum, you will get a lot of threads.
If this is what is application is going to do, take a look at a ThreadPool. This isn't an existing class in the Java API. You will have create one by yourself.
A ThreadPool is another Thread that manages all your other Threads the way you want. You can set a maximum number of running Threads. And in that ThreadPool, you can implement a system that manages the Thread priority automatically. Eg: You can make that older threads gain more priority, so you can properly end them.
So, if you know how to work with a ThreadPool, it can be very interesting.
According to java.lang.Thread API, you should use interrupt() method and check for isInterrupted() flag while you're doing some time-consuming cancelable operation. This approach allows to deal with different kind of "waiting situations":
1. wait(), join() and sleep() methods will throw InterruptedExcetion after you invoke interrupt() method
2. If thread blocked by java.nio.channels.Selector it will finish selector operation
3. If you're waiting for I/O thread will receive ClosedByInterruptException, but in this case your I/O facility must implement InterruptibleChannel interface.
If it's not possible to interrupt this action in a generic way, you could simply abandon previous thread and get results from a new one. You could do it by means of java.util.concurrent.Future and java.util.concurrent.ExecutorService.
Cosider following code snippet:
public class RequestService<Result> {
private ExecutorService executor = Executors.newFixedThreadPool(3);
private Future<Result> result;
public Future<Result> doRequest(){
if(result !=null){
result.cancel(true);
}
result = executor.submit(new Callable<Result>() {
public Result call() throws Exception {
// do your long-running service call here
}
});
return result;
}
}
Future object here represents a results of service call. If you invoke doRequest method one more time, it attempts to cancel previous task and then try to submit new request. As far as thread pool contain more than one thread, you won't have to wait until previous request is cancelled. New request is submitted immediately and method returns you a new result of request.

Categories