replace execution thread with new thread java - 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).

Related

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.

Why is there a limitation to start a Thread in JAVA only once even if the thread is completed its execution and terminated [duplicate]

I was reading about threads and found that we can't call the start method twice on the same thread instance. But I didn't understand the exact reason for the same. So why can't we call it twice or even more times?
In my opinion the Thread object is your "handle" for the actual running context. If you allow creating many concurrent executions associated with the same java.lang.Thread, what would you expect getStackTrace() and getState() methods to return?
I suppose that Thread class could have been designed to allow spawning multiple running contexts, but its API would be less simple and clean.
You want 1 instance for 1 thread, as that thread has internal state it will manage.
Consider threads as a kind of resource. It usually does not make sense to have 1 instance refer to several resources - (just as you can't have a java File object refer to more than 1 file).
It would also get you in all sorts of trouble if you started a thread twice, and you either inherited from Thread and made some instance variables that now more than 1 thread accesses, - same thing if you create the thread from a Runnable. Atleast the API doesn't make it a no-brainer to do that screw-up.
Take a look at the states a thread can be in , here http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Thread.State.html
Basically, the only time you can start a thread is when it is in the NEW state. And none of the other states can make it transition back to NEW
A Thread is not the same thing as a thread.
A (little-t) thread is an independent execution of your code. A (Big-T) Thread is a Java object that can be used to start, and manage the life cycle of a little-t thread.
Suppose you were hired to write code for an insurance company, and you defined a (Big-A) Accident class to represent a (little-a) accident. Somebody asks you, "Why can't I re-use an Accident instance?"
Well, an accident can only happen once, right? Even if the exact same thing happens to the exact same drivers and cars in the exact same way on a different day, it's still a different accident, right?
according to thread life cycle, once thread is 'dead' you can not restart it.You only can start new thread invoking start() method.
Thread can be bought to Running state from Runnable state not from Dead state.
This is my opinion, It is due to Thread id. Thread scheduler is identifying the thread through the thread id. It is unique real number. Please find below code,
public class StartTwice extends Thread {
public void run() {
System.out.println("running...");
}
public static void main(String[] args) {
StartTwice start1 = new StartTwice();
System.out.println("Thread id: " + start1.getId());
start1.start();
start1 = new StartTwice();
System.out.println("Thread id: " + start1.getId());
start1.start();
}
}
Output is:
Thread id: 10
Thread id: 11
running...
running...
When I re-instantiate the start1 object. A new thread id is created.
PS: Even a thread is done, we can't use the same object (thread id) second time.
Until or unless the JVM is reuse that id.

Cleaning up stopped threads

I have a state machine, which is used by many threads to manage the states of a game. I need to be able to clean the threads if something happens and an instance of a game does not change state for whatever reason.
How could i do this, i have the state machine?
If I'm getting you properly you mean to terminate threads given an event and check out if a state doesn't change. You could do it in a number of ways. Let me suggest you a possible solution.
1 - A simple way to terminate your threads would be to put those threads in a list, array, etc. a way to identify what threads you want to terminate.
2 - Create a method that terminateTheadList(...).
3 - To terminate them a way to do it would be to use the java.lang.Thread .interrupt() method. Iterate over your Thread list, array,etc. and interrupt() them. Then once you get the exception allow the thread to terminate.(that is to say, do not catch this exception and loop).
4 - To check you if the instance of the game create a new thread (this one should not be in your thread terminate list) that checks out that instance game and puts the last time this changed. Sleeps and checks out again. if the instance haven't changed call your terminateThreadList method again.
I hope this helps

Does creating a new Thread have a side effect of flushing the cache?

I want to know whether creating a new thread in Java triggers a cache flush. Suppose I do something like this, in this sequence:
A thread runs and sets a variable X.
The thread creates a new thread.
The new thread accesses X.
My question is this: is the new thread, either at the time it is created or at the time it begins execution, guaranteed to see the update made to X by the old thread in step 1? I understand that if the old thread changes the value of X in the future, it is not guaranteed that the new thread will see these changes. That's fine. I just want to know whether the new thread will see the right values when it starts without need for explicit synchronization.
When I first decided to look into this topic, I thought a simple google search would immediately reveal the answer, but for some reason, I can't find any result that addresses this question.
Yes, it is.
In java, there is 'happens-before' relation that specifies what memory effects are visible between two actions. If "A happens-before B", then action B is guaranteed to see all changes done by action A.
Starting a thread creates 'happens-before' relation between "thread.start()" call and all code that executes on new thread. New thread is therefore guaranteed to see memory effect of changing variable X on first thread.
For quick overview of happens-before relation, see Memory Visibility part of java.util.concurrent package overview. In your case, interesting bits are:
Each action in a thread happens-before every action in that thread that comes later in the program's order.
A call to start on a thread happens-before any action in the started thread.
More links if you are curious:
Java Memory Model is described in Chapter 17 of the Java Language Specification
Java Memory Model FAQ
Everything else about JMM

Making a single thread execute to completion

I was asked this question in an interview - not sure if it makes sense.
You have several threads of same priority started and running, how do you make sure that a particular thread among those is run to completion first?
You can't use wait() and sleep() trick on other threads..
EDIT:
Modifying the other threads is not allowed.
have one thread join() the other
Since you are not allowed to modify the threads, you will have to suspend the waiting threads and join() on the thread that must complete first.
I'll leave the following (I answered before the clarification about modifying the threads was added) for completeness, but under the clarified constraints of the problem these methods would be disallowed:
Have each of the other threads call join() on the thread that should complete first. This will cause them to wait until that thread has terminated, but using considerably less CPU time than a sleep() loop would.
Thread first = new FirstThread();
Thread after1 = new AfterThread(first);
Thread after2 = new AfterThread(first);
In the run method for AfterThread:
first.join();
// Do the rest of this thread's code
You can also pass a timeout to join().
An alternative method might be to create a lock that only a particular named thread can acquire, until after that named thread has acquired and released it once.
It's deprecated and inherently unsafe (so you should never use it), but you could suspend() all the other threads, then join() on the one you want to finish first, then resume().
I'm not sure if that's what they're going for. If it is, I would doubt either their interview skills or their Java knowledge.
The "good" solutions that I can think of require at least trivially modifying the code that the threads are going to run. Are you sure that it is off limits to modify those threads?

Categories

Resources