Java: How to pause 1 class from running? - java

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

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.

Is blocking main method in Java always bad?

We have an application that's continuously running. Nothing much goes on in the main method except initializing a few background threads. The background threads process socket events as they occur. Apart from the time the socket events are being processed, app remains in the idle state.
Main
Start Thread 1 -> while(socket connection 1 is good) -> process events
Start Thread 2 -> while(socket connection 2 is good) -> process events
Start Thread 3 -> while(socket connection 3 is good) -> process events
Start Thread 4 -> while(socket connection 4 is good) -> process events
while (true); // block main thread from exiting. Otherwise, periodic GC calls kills the app.
As the primary function of my app is to process events and there is not foreground tasks as such. Does blocking main thread is bad in my case? What are some other alternates?
the main thread is just the first thread, and as such is not different from any other thread. If you block it, it means waste of memory occupied by this thread (about 1MB) and nothing more. So I would just return from the main method, if there is no job for this thread.
I noticed a comment in your code: block main thread from exiting. Otherwise, periodic GC calls kills the app. The comment is wrong. GC calls cannot kill the application. I suspect other threads are started in daemon mode, and so the enclosing process does not wait for them to finish.
If you describe in more details when the whole process must end, we could make more sensible advises.
Since your main thread does busy waiting it will require thread scheduler to it (main thread) into list of scheduled threads. And if your machine where you are running your app has less then 4 CPUs then your event processing threads will suffer.
There are a lot of other ways to block your main thread without busy waiting. Thread.join() as mentioned above is one of them. You can also use Future.get(), or ExecutorService.awaitTermination() if you use high level concurrency objects.
Yes, it's a bad design. Use a ExecutorService and add the threads to it.
Blocking in the main method (or from any other thread) should be avoided. The problem you are running into – how to create some threads and keep the JVM running until those threads finish – can be solved in better ways.
If you create a new Thread and call setDaemon(false), then you won't need to do anything with sleeping or waiting. By setting the thread to be non-daemon, the JVM will stay running until that thread completes. From the Javadoc:
The Java Virtual Machine exits when the only threads running are all daemon threads.
Here's an example thread class that tries to sleep for 2 seconds, then prints out a message:
class ExampleThread extends Thread {
#Override
public void run() {
try {
sleep(2000);
System.out.println("done sleeping");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
If you call it like this – by setting daemon to false – you will first see
output thread started, followed by 2 seconds of nothing, then output done sleeping.
public static void main(String[] args) {
ExampleThread t = new ExampleThread();
t.setDaemon(false);
t.start();
System.out.println("thread started");
}
If you replace t.setDaemon(false) with this t.setDaemon(true) – so that the new thread is in fact a daemon thread – then you will see output thread started followed by immediate JVM termination.

preempt one Thread for another on run-time in java

how to start and run a new, most important, thread by stopping current processing thread in JAVA. i.e. a current thread's processing is going on and we want to stop or halt this thread for some time and execute a new thread.
There is no such fine grain control over threads in Java. You normally try to stay away from thread priorities, as it generates brittle system. But if you absolutely must, you can change a threads priority and it will be taken into consideration by most systems.
Thread.currentThread().setPriority(Thread.MAX_PRIORITY-1); // make it important
You can pause other threads only if they do support this. But keep in mind that a paused thread still does occupy all memory and resources. The work needed to pause and resume a thread might not be justified by the gains. (In this regard priorities are better).
To pause a thread you can for example use a lock which you aquire in the worker thread. Whenever it is locked (by a more important thread) it will make the worker thread pause (with no CPU usage).
class WorkerThread {
Semaphore sem;
void checkForPause() throws InterruptedExec{
synchronized(sem) { // make sure unpauseThread() cant release it
sem.aquire(); // will block when pauseThread aquired one
sem.release();
}
}
void pauseThread() {
sem.aquire();
}
void unpauseThread() {
synchronized(sem) { sem.release(); } // only release after checkForPause()
}
work run() {
while(true) { // do something in a loop
checkForPause();
// do actual work in small steps
}
}
}
Now the WorkerThread instance can be controled with pauseThread() and unpauseThread().
BTW: in older Java there was Thread#suspend() and Thread#resume() but it should not be used in modern programs. In the deprecation notice is some alternative code.
You need to use Thread's Class join() method.
Let say if you have 2 threads T1 and T2.
When you call T1.start() , T1.join() and call T2.start() then T1 will wait until T2 finishes it work and after that T1 is going to execute.
Please go through the below link for more details.
Thread join() method

Is it always necessary to wait for every thread to terminate before actually closing main one?

Suppose I have a main thread and a normal thread, whose execution lasts more than the former one.
Something like it:
public class Test{
private int count;
public void doTest(){
(new MyThread()).start();
}
public static void main(String[] args){
Test t = new Test();
t.doTest();
}
private class MyThread extends Thread{
public void run(){
while(count < 100){
count++;
..wait some secs ...
}
}
}
}
Is it wrong to just leave code like that? Or would it be more correct perform a join() on the thread so to make sure that it correctly ends?
This is one of the question, for which the answer is: It depends.
There is no technical reason to have the main thread running till all other threads are terminated. In fact, you can handle the main thread like every other thread. As I recommend to not have a thread keeping alive when it already has done its business and can be terminated, a main thread that only starts other threads should simply terminate after starting the others.
Remind: The JVM itself is not terminated when the main thread terminates. The JVM will only terminate when all non-daemon threads are terminated.
I think you maybe also looking for a scenario when it is "not okay to exit before all thread exit" / "wait till all threads exit, and then exit the main program".
While developing games, at least in java , we do need to take care that all thread exit before the main program exits . If you ask why, then let me explain you with an example which should clear things for you.
If there are 3 threads, controlling different aspects of game.
Thread 1: Controls the game background sounds/music/audio.
Thread 2: Controls the Artificial intelligence .
Thread 3: Controls the Graphics Rendering .
And consider this scenario, if the user closes his game, and if the threads are not waited upon before closing then there can a be case where in the main window of the game is closed i.e. Thread 2, Thread 3 but not Thread 1. So you will have the game music still playing even when the game window is not seen. That would be pretty embarrassing for any game developer.
It is perfectly fine.
No join or System.exit necessary.
Each thread lives its own life. As long as at least one thread is running, the program keeps running.
The JVM will automatically exit as soon as there are no more non-daemon threads running.
If you don't call setDaemon(true) before launching the thread, the JVM will automatically exit when your Thread is done. No need to call join() on the Thread, if all you want is for the process to end as soon as your thread ends.
Unless the thread runs in an endless loop, it will end at some time, the question is whether you want to wait for the termination of that thread or not? You may want to wait If the further processing depends on the result of thread you have started. If that thread just does some work and ends then just leave it.

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

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.

Categories