Multithreading Java - Joins - java

I am new to multithreading in java and would like to confirm that the following code works as I think it does.
// Inside class Menu
for (User user : users)
{
UserThread uT = new UserThread(user);
uT.start();
try
{
uT.join();
}
catch (InterruptedException e)
{
System.out.println(e.getMessage());
}
}
So for each user inside an arraylist called users, a new thread is created and started. Then uT.Join() is used to tell the Menu class to wait for the threads to finish before it can continue. Is that correct?
The multithreading works successfully without uT.Join() however the Menu class will display a menu and it will clash with the other threads that also print out something. Also without the join, the threads don't always print out in the same order, but when using join, they always seem to print in the same order, which is what is worrying me.
What I am unsure of is, does uT.Join() only ask the main thread that displays the menu to wait or does it also ask the other user threads to wait? I want my threads to be concurrent and not to obstruct each other in any way.
PS: I do realise there are multiple topics about this question and I apologise for adding another to the collection, but I was unable to find one that I could perfectly understand.
Thanks for reading, if I have missed any information that should be added please don't hesitate to inform me.

The way you designed the code is wrong. Using Thread#join will stop the execution of the current thread until the thead being executed finishes.
This is how the code should be designed:
List<UserThread> userThreadList = new ArrayList<UserThread>();
for (User user : users) {
UserThread uT = new UserThread(user);
uT.start();
userThreadList.add(uT);
}
for (UserThread uT : userThreadList) {
try
{
uT.join();
}
catch (InterruptedException e)
{
System.out.println(e.getMessage());
}
}
Note that it will be better to use ExecutorService for these tasks rather than trying to implement it manually.

Not quite, since your join is in the same loop as the the start, it will wait for the thread to finish before starting the next one.
You'd need two loops to accomplish that. One to start the threads and store them in some collection, and another loop to iterate through the collection and join each thread.

Related

Prevent Thread Subclass from waiting

I'm making a coding game for the Java class I TA. The game is to manage a fleet of trucks (Truck extends Thread) on an undirected graph to deliver parcels to their various destinations using as little time/fuel as possible. The student extends an abstract manager class that fills in the gaps in the Truck's behavior (what to do upon reaching a destination, etc). The truck class's run method is a event loop that waits for user instruction and then follows it when it receives travel destinations. Here's the event loop:
#Override
/** The Truck's main running routine. While the travel directions are empty,
* Waits for more instructions in WAIT_TIME intervals. While the travel directions
* are not empty, pops off the next travel direction
*/
public void run(){
while(game.isRunning()){
setGoingTo(null);
while(travel.isEmpty() && game.isRunning()){
try{
Thread.sleep(WAIT_TIME);
}
catch (InterruptedException e){
e.printStackTrace();
}
setStatus(Status.WAITING);
game.getScore().changeScore(Score.WAIT_COST);
}
while(!travel.isEmpty() && game.isRunning()){
Edge r = getTravel();
try {
travel(r);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
The first inner while loop loops while there are no travel instructions to follow. As you can see, every WAIT_TIME milliseconds (a frame), the score is decreased by the wait cost - the cost of the truck idling.
I realized, however, that a way for a potential solution to get around this cost is to tell the truck (thread) to wait while it doesn't have instructions, then notify it once the user has computed instructions for it. I'd like to prevent this programmatically, rather than just put in the instructions not to do it.
Is this even possible? Perhaps a method in the thread class to override? Can a class that extends Thread be prevented from waiting (on anything?) I'd settle for any kind of exception being thrown if a truck thread tries to execute .wait().
Thanks for reading and for any suggestions for how to tackle this gap in the rules! The game will be up on a public repo soon if you want to try your hand at it.
I don't have a solution for the exact question you asked (how to prevent wait), but a suggestion that is kind of too long for a comment:
How about measuring the time between the start of the first while loop and the end.
long starttime = System.currentTimeMillis();
setStatus(Status.WAITING);
while(travel.isEmpty() && game.isRunning()){
try{
Thread.sleep(WAIT_TIME);
}
catch (InterruptedException e){
e.printStackTrace();
}
}
long endtime = System.currentTimeMillis();
long waittime = endtime - starttime;
game.getScore().changeScore(Score.WAIT_COST * (1 + waittime / WAIT_TIME));
Even if the thread is sent to sleep, the score will change according to the ellapsed time. You will just not have a live game score update.
I'm pretty sure you can't prevent .sleep() or .wait() because you can't override or tamper with them. So the only way is monitoring for them.
I don't know of a method inside the thread but from outside the thread (for example from a monitoring thread) you can get the thread staus with
Thread.getState()
if someone called sleep on the thread or the thread is waiting becuase of a wait call the result should be Thread.State.TIMED_WAITING. Then all you have to ensure is that the monitoriong thread knows it were the students that called sleep and not you (a private flag for example).
The monitoring thread can then of course take any counter measures you want like throwing an Exception or simply silently decucting points.
Relevant docs :
http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.State.html#TIMED_WAITING
http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#getState()
I wonder whether having a Thread per Truck is the right approach. Are you trying to teach them about threads? or are you trying to teach them about graph algorithms and heuristics? (If the Single Responsibility Principle applies to homework assignments, then the answer should be one or the other, but not both.)
If the emphasis was on algorithms and heuristics, then I would write a single-threaded program where the main loop executes a series of "moves". In each move, it would ask each of the truck objects what the truck wants to do next, and then it would either move the truck accordingly, or it would flag the assignment as invalid if the truck asked to do something that did not make sense.
In my version, the "time" in the simulation would be completely decoupled from real-time, so if some student put a Thread.sleep() in her/his strategy routine, it would not have any effect on the outcome of the program; it only would make the program take that much longer to run. (Of course, I would run them all under control of a batch script that would abort any assignment that took longer than... say, three minutes.)

Waiting before returning within Java

Right now, I have a piece of code that contacts another server asking if an item is in a list, and returns a boolean value based on that returned value.
The code goes like so:
public boolean checkIfOnline(int accountId) {
//First loop is incase if someone is already checking. Second is for the checking that this account is doing.
while (isCheckingIfOnline) {
try {
Thread.sleep(1);
} catch (InterruptedException ex) {
}
}
isCheckingIfOnline = true;
sendCheckIfOnline(accountId);
while (isCheckingIfOnline) {
try {
Thread.sleep(1);
} catch (InterruptedException ex) {
}
}
return onlineResponse;
}
The onlineResponse and isCheckingIfOnline are changed within a method that handles what the other server returns, and this is the method I've thrown together to have the system wait for the other server to respond. Obviously, this is very flawed, as when this method gets called often, it'll slow down the system since it only allows for one query at a time, when it should allow for multiple queries to be executed simultaneously.
What other method could I use that accomplishes what the above code does, but allows for more than one query to run at once?
Edit: To clarify even more, checkIfOnline takes an account ID, and asks another server is that account ID is on a list, which that other server responds to the current server if the account ID is or is not on the list.
Sounds like you would want to make use of the ExecutorService in Java 6+.
The ExecutorService requires you to submit to it a class that implements Callable. When you submit a Callable to a ES, you receive back a Future that you can use to do a number of things, including cancelling the process or getting a result from a completed process.
It's a little hard for me to understand exactly what you are trying to achieve with your code and why you're threading that particular part. That being said, if you want to achieve concurrency there, you'd have to:
submit a Callable to the ES that does the online checks & query;
provide a way for the Callable to notify the your application that it has finished it's execution.
It will not be sufficient to simply submit the task and call Future.get() on it because whatever thread makes that call will be suspended until the task is completed.
You'd need to either allow the Callable to invoke a callback, or thread the class that performs the submission of the task and allow it to sit and wait for the future.get() method to return a result.
Good luck :)

long running application (tail like)

I want to write an tail like app. Now this app, scans a file for changes in the background and fires events in case something changed.
I want to run my application until the user requests to exit it by pressing ctrl + c (working by default). I do not want to create a lot of CPU load just by doing an endless while(true) loop like I'm doing ATM:
try {
// thread doing the monitoring
thread.start();
// forcing the programm not to exit
while (System.in.available() == 0) {
Thread.sleep(5000);
}
} catch (final IOException e) {
e.printStackTrace();
}
Does anyone know a more elegant/the right approach for this?
I'm not sure why you are using a thread in the first place, the 'tail' unix script is simply a while(true) loop with no exit condition. It watches the file and prints changes if any is detected. I think by default it pauses 1 second, so basically:
while(true) {
// Code goes here. Watch file, System.out.print if it changes
Thread.sleep(1000);
}
No need for a thread. But to answer the question about the best way to keep your app alive: Simply don't return from the thread's run() method. You don't have to join the thread, the application will stay in the foreground as long as it has one non-daemon running thread.
If you want to read the System.in without busy-waiting, that's very easy to achieve. InputStream has blocking semantics so all you need to to is call one of the read methods and it will block until there is input available. If you are scanning text input, I'd advise BufferedReader.readLine. Also, do that on the main thread, no point in starting another one.

why my android project raise CPU usage range from 60% ~ 100%?

Hello I'm making a chat application in android
so overall, I have a service which contains lots of classes and threads.
in my service, i had socket input read class, socket output writer class, and pinger that in summary have 6 threads.
Actually, i'm very new with this problem, well i can say i have no idea what makes a program occupy high percentage of CPU processes. is it cause too many static variables maybe? or too many running threads maybe, or too many local variables maybe?
I don't know exactly what is going on...?
So, please share with me your experiences and knowledge
UPDATE
public void run() {
while(isRunning) {
try {
Thread.sleep(500);
if(!startCheck) {
//Log.v(TAG, "SocketQueue: "+socketTaskQueue.size()
if(socketTaskQueue.size() > 0) {
processSocketTask();// TODO
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
so basically, i made my threads like above example.
so, i have a vector called socketTaskQueue, and this thread job's is to check whether there's a socket task or not. if it does, then it will execute processSocketTask function that will get the top element of the vector queue and then remove it.
UPDATE
T.T this post is embarrassing! i forget to put Thread.sleep() in some of my threads!
SORRY FOR BOTHERING YOU GUYS! :p
It is caused, usually, by threads that use CPU even when they cannot accomplish useful work. For example, when a thread is waiting for something to happen, does it wait in a way that uses no CPU? Or does it keep waking up needlessly even before it can do work?
It can also be caused by threads that do work in extremely inefficient ways.

Adding return statement to watchable in Java

How to add return statement to watchable method in Java and still be working properly. I want always to be searching for files, OK I have that. But now I want to get the return, but when I add return statement everything goes down the function stops and the watchable stops too .. Any ideas ?
for (;;) {
WatchKey key = watcher.take();
for (WatchEvent<?> event: key.pollEvents()) {
if (event.kind() == StandardWatchEventKind.ENTRY_CREATE) {
System.out.println(event.context().toString());
}
}
Here is the loop which always searches, how to return from It and still to be working?
I think you mean you want to perform other actions in the program, while still having the watcher run. For that, you would need to create and start a new Thread for the watcher:
Thread watcherThread = new Thread(new Runnable() {
public void run() {
// Watcher loop code goes here
}
});
watcherThread.start();
As #dlev says, if you want your application to process watch events at the same time as it is doing other things, then the way to do it is in a separate thread.
This leaves you with the problem of "returning" the information. (I presume that simply printing the information to standard output is not any use to you.)
As you observed, you can't use return because that will terminate the loop.
The basic answer is that you need to put the information somewhere so that the rest of your application can access. For example:
You could create a queue object (e.g. a ConcurrentLinkedQueue), have your watcher enqueue the data, and have some other thread dequeue it and process it.
You could have the watcher process the event payload itself and put the results into a shared data structure.
However, without more information, it is difficult to decide what approach will be best for you.

Categories

Resources