In Akka documentation, there was a part talked about "The illusion of a call stack", um attaching a picture for a part of it. I don't get what he is talking about, I mean if the main thread in java created a new thread and start it if any exception thrown in the created thread the main thread will be notified, so why he is saying that the "caller" will not be notified?!
I mean if the main thread in java created a new thread and start it if any exception thrown in the created thread the main thread will be notified
That is false. Unless the main thread explicitly sets up an uncaught exception handler, it will not be notified of any exceptions in thread it launches (and the uncaught exception handler will also not run in the main thread, so technically the main thread isn't notified at all).
The "illusion of a call stack" is about the fact that the conceptual flow of logic no longer fits the physical call stack when you use things like work queues to schedule separate tasks on other threads.
The actual call stack of any failing sub-task on such a queue will show code related to handling the queue but will not show the calls stack related to the code that initially queued the task which is arguably the more interesting one in many cases.
Related
Problem:
I wanted to know when a RunTimeException is thrown in run method of thread, will thread local of that thread be preserved? Answer to this question lies in what I'm asking below. So with that said, if thread dies(when exception is thrown) it's thread local snapshot get's cleared up or if thread does not die what happens to thread local in that case. Do we need to programmatically handle that?
Scenario:
During heavy load, request came in and processing took way too long and before response was created, async context times out. What happens in this scenario? What happens to the thread that is processing the request?
Here's more details :
I've been researching on how ThreadPoolExecutors internally work. What I'm curious to know is what happens when a RunTimeException is thrown in run method of thread. Does it get killed and ThreadPoolExecutor ends up creating brand new thread? Or JVM somehow does not let that thread to die, so that it can reused in
the pool. I think the thread dies and so does it's ThreadLocal snapshot.
I wanted to get some insight on exactly how ThreadPoolExecutor handle exceptions and how life cycle of a particular thread revolves around that.
Thanks for your help!
Thanks everyone! I got my answer.
Thread dies when an exception is thrown. Only catch here is if we reference a thread id in thread local that can cause a thread leak if that is not cleared properly.
Thread id can be reused as per java docs. In my case I was putting putting some stuff in thread local referencing to thread id (Thread.currentThread.getId). Best way to clear that up is to override afterExecute(java.lang.Runnable, java.lang.Throwable) and clean up things in there.
From java docs:
public long getId()
Returns the identifier of this Thread. The thread ID is a positive long number generated when this thread was created. The thread ID is unique and remains unchanged during its lifetime. When a thread is terminated, this thread ID may be reused.
So, I have a main thread that spawns a bunch of "worker-threads" that works alongside it for the duration of the process. What I want is that if a worker-thread dies from an exception or whatnot, the main thread should also throw a runtime-exception and die peacefully.
This can be achieved by catching the exception in the worker-tread and setting an error-flag before exiting. The main thread then polls this flag and throws an exception if it's set. This can be done by try-catch or setting an exception handler.
My question is whether there's a simpler way that doesn't include polling in the main thread. Something that goes automatic if you know what I mean.
Edit:
Well, many claim that setting a handler is the answer and that this is a duplicate. Well, unless I'm mistaking things here, the handler is executed by the thread that throws the exception in the first place, so I still have to set a flag to kill the main thread. I thought this was clear. SO let me clarify;
What I want is that if a worker-thread dies from an exception or whatnot, the main thread should also throw a runtime-exception and die peacefully, without using flags, but have it done "automatically"
Have a CountdownLatch in the main thread, have it wait on the CountdownLatch.
When a thread exits decrement the CountdownLatch. When that happens have the main thread act appropriately.
I am developing one code in which I have one parent thread and one child thread.Now, my scenario is like mentioned below,
Parent thread start the child thread
after starting the child thread it continuous to work what it is doing.
Now one time occurs that child thread want to call the method in the main thread
then it call asynchronously the main thread with that method.
I also want to clarify that I know the concurrency package in java but it is doing synchronously i.e. main thread have to wait for the child thread till it complete the execution,but I want the main thread to do continuous work while child thread executing.
My implementation is like SwingWorker Thread in java
You don't get to "call a method in the main thread". The only thing you can do is implement a specific mechanism whereby the main thread, by its own initiative, executes a method on an object which was provided by the child thread.
The above roughly describes what the Swing's mechanism does: the "main" thread (in that case, the Event Dispatch Thread) dequeues objects from a global queue and, if the object's type is appropriate, invokes the run method on an associated instance of Runnable.
Main point: in Swing the EDT doesn't "continue to work what it is doing"; it specifically waits for other threads to tell it what to do via this mechanism and otherwise just blocks, doing nothing at all.
I think title itself says what the my question is...
AFAIK, in Java, when work of a Thread is completed i.e. run() method has completed executing, Thread itself will finish and dies.
So, When my Activity(I mean UI) is idle for a long time, what the UI thread will do? does it sleeps? or does it do any other work?
Thanks to all...
I believe the question is not really about Java threads in general, but about the Android "main thread" (also called the "UI thread").
To quote from the JavaDoc for the Android Handler:
When a process is created for your application, its main thread is
dedicated to running a message queue that takes care of managing the
top-level application objects (activities, broadcast receivers, etc)
and any windows they create. You can create your own threads, and
communicate back with the main application thread through a Handler.
This is done by calling the same post or sendMessage methods as
before, but from your new thread. The given Runnable or Message will
then be scheduled in the Handler's message queue and processed when
appropriate.
In other words: The main thread is responsible for dequeuing messages/runnables from a queue and processing them. That main thread is blocked while the queue is empty (since there is nothing for it to do). If you use a Handler that was created in the main thread, that Handler's messages and runnables will actually be added to the same queue used by the main thread. Normally, the main thread will run as long as the process does.
Note: An Android app can actually have multiple processes, and each one will have its own main thread. However, most Android apps will only have one process (and therefore one main thread).
I'm working with a GUI and I'm using
Thread.sleep();
in some of the classes, and I'm wondering if I need to create a separate Thread for my Main class (the GUI class), or if each class has a separate Thread by default. Note, the reason that I bring up Thread.sleep(); in the first place is that when working with GUI's Thread.sleep(); pretty much freezes your GUI. Anyways my main question is do I need to create a separate Thread for my Main class or if each class has a separate Thread by default.
Thread.sleep() is a static method of Thread class. Hence, whichever class you place in a method, during runtime, if a thread call flow encounters this class method where Thread.sleep() in invoked, the thread will be blocked for that amount of time.
Your Question:
Anyways my main question is do I need to create a separate Thread for my Main class or if each class has a separate Thread by default.
each class has a separate Thread by default -- INCORRECT Statement
-- Thread class is not inherited by every class
-- In normal sense, Thread is a call flow. It executes whichever class it encounters thru its method calls.
-- Class and Thread are 2 separate concepts.
---- Class is a definition of an entity,it cannot run by itself, it can be loaded, instantiated with data, method calls can be done and garbage collected.
---- Thread is an execution entity at run-time.It can be started, runnable, blocked, stopped. To support this concept, Java has provided Thread class or Runnable interface to extend/implement respectively.
do I need to create a separate Thread for my Main class?
-- your mainclass will be executed in a MainThread which is instantiated and started by your JVM.
-- It is better to define a seperate user-defined Thread to start your GUI.
-- If either in the MainThread (or) user-defined Thread, if it encounters Thread.sleep() during call flow, that particular thread will be blocked.
One more thing, your question is not clear on your need for usage of Thread.sleep(). You just have given a reason of the resultant usage of it but not the need for usage.
From javadoc for Thread:
Causes the currently executing thread to sleep (temporarily cease
execution) for the specified number of milliseconds, subject to the
precision and accuracy of system timers and schedulers. The thread
does not lose ownership of any monitors.
Don't mind that the sleep() method is static, it is executed for the thread in which you call it. So if you call it from GUI, it puts your main UI thread into sleep, hence freezing UI completely.
by default the program does not have more than one thread. there should be only one class which has a main method. it does not matter it is a ui application or any other type of application.
please post the details in what scenario you want to use the sleep function.
When a java class is created automatically 3 thread are created by-default with it.
1.Main Thread
2.Thread Scheduler
3.Garbage Collector thread
Please watch this explanatory video to understand what a Thread actually is.
In this example the Thread is the music box, your code is the sheet of paper, and the processing time granted to a thread is the rotation of the handle.
So your main-class code (sheet-of-paper) is inserted into a thread (music-box) generated by the JVM and execution is started (handle rotates). Once you call sleep(1000) "rotations of the handle" is paused for 1 second, and so is the execution of your code. Thread.sleep() is just a short-cut to Thread.getCurrentThread().sleep().
If you now have several threads (music-boxes), you can of course pause one while another still runs. So if you have a main thread and a GUI thread, you can pause the main thread and your GUI will work fine (unless it actually tries to access the main thread). If you however pause the GUI thread, it will appear to be frozen.