Launching threads from within while loop, what happens? - java

I want to have a while loop that launches a thread on each loop,
I am using the following to launch the thread, do I need to have a unique identifier for each thread or becuase it is launching from different loops will it launch ok, or will it overwrite the previous launch as they are using the same identifier?
while(x<y){
Runnable r = new Rule1("neil", 2, 0);
new Thread(r).start();
x++;
}

It will work fine.
Your threads do not have any identifiers at all.
The r variable is a normal (and temporary) variable; you are passing its value to the Thread constructor.
The runtime isn't even aware of the variable.

It will launch multiple threads. The only "unique identifier" for the thread is the ID returned by Thread.getId(), and you don't get to assign that. Even the thread name doesn't need to be unique. In other words, there's no unique identifier which is being reused here.
Certainly the fact that you're assigning the Thread reference to the same variable on each iteration doesn't mean the threads will care in the slightest.

While you do not need to create a unique identifier for each thread (framework will take care of it) it is best practice if at all possible to name your threads in relation to what they are doing so that when you begin debugging via logs/jvisualvm you are aware of the threads purpose.

Related

Why is this working? (generating values in main thread and consuming them in some other background thread in Android)

As far as I know, threads copy variables in their local cache.
What I'm doing is, I'm getting values in the main thread and then I'm consuming them in some other background (renderer) thread. Like this-
class MySurfaceView ... {
private var someValue = 0
// Called from the main thread
fun updateValue() {
someValue++
}
fun render() {
Thread {
// Here someValue variable is consumed
// and it's always up to date.
....
}.start()
}
}
So, inside the runnable passed to the thread started inside render(), 'someValue' is always up to date and I didn't even mark it volatile. If threads copy variables to their local cache then why is it happening? Is it because an implicit reference of the outer class is being kept and the value is coming from there (if this is true, then in cases like this, where I have one generator and multiple consumer threads, would it always be safe to not mark the field which is updated only by the generator thread as volatile? As read/write operations on volatile is costly)?
The same thing also happens when I start a coroutine and try access 'someValue' inside it.
threads copy variables in their local cache.
This is not true, which explains your findings. Basically, you confused the liberties an implementation may exercise with guarantees the specification provides. The Java Memory Model (which Kotlin follows as well) simply gives the implementation the freedom to do whatever it likes with state that doesn't get shared through synchronizing actions. It may store it on the stack or in a register, and it may also work with the original on the heap.
One especially relevant detail is that println() is a synchronized method, so if in your actual code you had printlns in both threads to see what's going on, you introduced synchronization that made the results come out right.
On the other hand, it's quite easy to see a program that takes this freedom, for example
Thread 1:
var runningFlag = true
while (runningFlag) {}
Thread 2:
sleep(1000)
runningFlag = false
Thread 1 is quite likely to go on executing forever, or even to be compiled similar to currentThread().join() -- doing no actual work, but never completing.

Stop running Thread By Name

I have a multithreaded application and I assign a unique name to each thread through setName() property.
Now, I want functionality to get access to the threads directly with their corresponding name to stop it.
How can i get that?
To find a thread you use this: https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/ThreadUtils.html (https://github.com/apache/commons-lang/blob/master/src/main/java/org/apache/commons/lang3/ThreadUtils.java)
But that gives you only a reference to the thread and you cannot simply terminate it (stop() is deprecated). Depending on what the Thread is doing maybe interrupting it is an option?
I assume you are trying to get to the thread (by its name) to call Thread.stop() on it. If that is the case - don't do that. The method is deprecated - see why.
This question has some suggestions on how to properly stop a thread.
If you really want to access a thread by name and you don't have a reference that can be used, you could use ThreadGroup and search the tree formed by groups and threads for the one with the correct name.
From the JavaDoc:
A thread group represents a set of threads. In addition, a thread group can also include other thread groups. The thread groups form a tree in which every thread group except the initial thread group has a parent.
Thus you should be able to call Thread.currentThread().getThreadGroup(), use getParent() to find the initial/root group, list all active threads using enumerate(Thread[]) and search the threads.

What is the use of ThreadLocal?

What is the use of ThreadLocal when a Thread normally works on variable keeping it in its local cache ?
Which means thread1 do not know the value of same var in thread2 even if no ThreadLocal is used .
With multiple threads, although you have to do work to make sure you read the "most recent" value of a variable, you expect there to be effectively one variable per instance (assuming we're talking about instance fields here). You might read an out of date value unless you're careful, but basically you've got one variable.
With ThreadLocal, you're explicitly wanting to have one value per thread that reads the variable. That's typically for the sake of context. For example, a web server with some authentication layer might set a thread-local variable early in request handling so that any code within the execution of that request can access the authentication details, without needing any explicit reference to a context object. So long as all the handling is done on the one thread, and that's the only thing that thread does, you're fine.
A thread doesn't have to keep variables in its local cache -- it's just that it's allowed to, unless you tell it otherwise.
So:
If you want to force a thread to share its state with other threads, you have to use synchronization of some sort (including synchronized blocks, volatile variables, etc).
If you want to prevent a thread from sharing its state with other threads, you have to use ThreadLocal (assuming the object that holds the variable is known to multiple threads -- if it's not, then everything is thread-local anyway!).
It's kind of a global variable for the thread itself, so that any code running in the thread can access it directly. (A "really" global variable can be accessed by any code running in the "process"; we could call it ProcessLocal:)
Is global variable bad? Maybe; it should be avoided if we can. But sometimes we have no choice, we cannot pass the object through method parameters, and ThreadLocal proves to be useful in many designs without causing too much trouble.
Use of ThreadLocal is when an object is not thread-safe, but you want to avoid synchronizing access. So each thread stores data on its own Thread local storage memory. By default, data is shared between threads.

replace execution thread with new thread java

I want to know how to replace current thread of execution with a new thread object in Java. Some more context, the new thread will be fetched from a concurrent hashmap of with unique key and value as thread objects . Unique key might be obtained from the current thread of execution.
You can't really "replace" the current thread with another thread, you can just add another thread and terminate the fist one. I don't know if you consider that replacing.
If you show us some code demonstrating how your "current" thread is being started and approximately what it's doing, then we might be able to give you some more pointers on how to either block the current thread (thus forcing it not to work) or to terminate that thread all-together (which are pretty much your two major options).

multi thread safe class

Question:
A) Write a thread safe class with methods doA(), doB(), doC(). Each of these methods must report the method name, time of invocation, and calling thread name.
B) Write a multi threaded driver that spawns 4 threads, and each thread must call every method – doA(), doB(), doC() – 10 times
I am assuming that it means doA(), doB(), doC() must be safe. But none of them mutate the shared state within the object, they just read object state such as method name, thread name and running time. So, do I need synchronize each method? For the counter within each thread, it is not shared.
I am a little confused here, which of state of the object needs protection?
Edit:
Do we need a mechanism to assure the running sequence of doA(), doB(), doC()? I dont think so.
From the sounds of it, your object will have no mutable state at all. Objects without mutable state are usually (not always, but usually) thread-safe without any additional locking. Of course, if there's additional requirements that do imply mutable state, the answer would be different.
How are you reporting the information? If it's to a console or any other resource that's independent of thread, there's your shared "state". Sort of. Some mechanisms for writing to a console will buffer lines, so you may not have problems, but over multiple lines you'll have to make sure that two don't write to it at the same time. For example, if I were to print:
Thread: A
Method: doA
Running Time: 4.6s
Then I'd want to make sure another thread doesn't start half-way through. Otherwise you may end up with something like this:
Thread: A
Thread: B
Method: doB
Running Time: 4.6s
Method: doA
Running Time: 3.2s
Not so helpful.

Categories

Resources