Java threads without affecting performance - java

Long story short; I've written a program that contains an infinite loop, in which a function is run continuously, and must run as quickly as is possible.
However, whilst this function completes in a microsecond time scale, I need to spawn another thread that will take considerably longer to run, but it must not affect the previous thread.
Hopefully this example will help explain things:
while (updateGUI == true) { //So, forever until terminated
final String tableContents = parser.readTable(location, header);
if (tableContents.length() == 0) {//No table there, nothing to do
} else {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
//updateTable updates a JTable
updateTable(tableContents, TableModel);
TableColumnModel tcm = guiTable.getColumnModel();
}
});
}
***New thread is needed here!
}
So what I need is for the readTable function to run an infinite number of times, however I then need to start a second thread that will also run an infinite number of times, however it will take milliseconds/seconds to complete, as it has to perform some file I/O and can take a bit of time to complete.
I've played around with extending the Thread class, and using the Executors.newCacheThreadPool to try spawning a new thread. However, anything I do causes the readTable function to slow down, and results in the table not being updated correctly, as it cannot read the data fast enough.
Chances are I need to redesign the way this loop runs, or possible just start two new threads and put the infinite looping within them instead.
The reason for it being designed this way was due to the fact that once the updateTable function runs, it returns a string that is used to update a JTable, which (as far as I know), must be done on Java's Main Dispatch Thread, as that is where the GUI's table was created.
If anyone has any suggestions I'd greatly appreciate them.
Thanks

As you are updating a JTable, SwingWorker will be convenient. In this case, one worker can coexist with another, as suggested here.

You have to be very careful to avoid overloading your machine. You long running task need to be made independent of you thread which must be fast. You also need to put a cap on how many of these are running at once. I would put a cap of one to start with.
Also you screen can only update so fast, and you can only see the screen updating so fast. I would limit the number of updates per second to 20 to start with.
BTW Setting the priority only helps if your machine is overloaded. Your goal should be to ensure it is not overloaded in the first place and then the priority shouldn't matter.

It's very hard to guess what's going on here, but you said "results in the table not being updated correctly, as it cannot read the data fast enough". If you really mean the correctness of the code is affected by the timing not being fast enough, then your code is not thread safe and you need to use proper synchronization.
Correctness must not depend on timing, as timing of thread execution is not deterministic on standard JVMs.
Also, do not fiddle with thread priorities. Unless you are a concurrency guru trying to do something very unusual, you don't need to do this and it may make things confusing and/or break.

So if you want your "infinite" looping thread to have max priority, why are you setting priority to MAX for EDT insted of you "most precious one"?
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
//updateTable updates a JTable
updateTable(tableContents, TableModel);
TableColumnModel tcm = guiTable.getColumnModel();
In this piece of code current thread will be and EDT, or EDT spawned one. Why not moving that line before intering whileloop?

Related

Can java cache strike when the thread is not put to sleep manually?

To make my problem/question easier to understand, I'll put it in a bullet list:
Have a volatile array.
Data is set to this array from multiple threads but the threads NEVER run at the same time.
I have a code like that in one of the threads (which don't execute in parallel):
{
myArray[0] = myData;
sleep(1);
doSomething(myArray[0]);
}
Now it sometimes (fairly well reproducible) happens that doSomething() does NOT receive myData but instead some data set once in another thread!
I am fairly sure that there's the Java caching mechanism striking here because even if the array is volatile, it's elements can stupidly not be made volatile.
This code section is very speed critical thus I would really want to avoid using AtomicReferenceArray as I also don't need atomic functionality.
However it was only a coincidence (debugging purpose) that I had sleep() just in there. It is not needed.
BUT I know that the CPU or Windows will randomly switch/sleep threads anyways. So does that mean that also without sleep(), I could run into this issue on long term and with bad luck?
It did not happen within ~20 minutes of testing time at least.
So does that mean that the JVM (and its caching) works differently if the CPU switches its thread and I don't make it sleep myself?
If the former is the case, does anyone have some suggestion how to avoid this problem?
Huge thanks in advance!
If you are sure that Threads doesn't run in parallel. Could you write the 3 line of code in synchronized block?
As all the variables which are in synchronized block, refresh the value from the main memory. So you will get an most recent updated value.

Is Thread.sleep() a waste of time for polling in Java?

Suppose I have a nametag, which is UI component in GUI program.
The nametag will constantly change its text based on the data.
If the user change his/her name data, then he/she will see the change in nametag.
For this task, my code looks like this:
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
while (true) {
String name = data.getName();
nametag.setText(name);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
Since the reaction time of 0.1s seems instant to people, I included Thread.sleep(100) for computer to take a break.
However, I am not sure if that helps the computer in terms of energy usage or something. Is sleep method in this case complete waste of time? No benefit at all?
Thread.Sleep has been used for many things it shouldn’t be used for.
Here’s a list of the common mistakes:
The thread needs to wait for another thread to complete
In this case no value, other than infinite, passed to Thread.Sleep will be correct. You simply don’t know when the other thread will complete using this method. If the thread completed after Sleep returned you’ll likely have synchronization problems. If the other thread completed before Sleep returned the thread was needlessly blocked for an amount of time rendering the benefits of multithreading limited or moot. In the control circumstances where you’ve tested this it may seem like it always works; it just takes a busy program to cause it to faile: a defrag program, a sudden influx of network traffic, a network hiccup, etc.
The thread needs perform logic every n milliseconds
As noted earlier, Sleep means relinquish control. When your thread gets control again isn’t up to the thread; so it can’t be used for periodic logic.
We don’t know why Thread.Sleep is required; but if we take it out the application stops working
This is flawed logic because the application still doesn’t work with Thread.Sleep. This is really just spackling over the problem on that particular computer. The original problem is likely a timing/synchronization issue, ignoring it by hiding it with Thread.Sleep is only going to delay the problem and make it occur in random, hard to reproduce ways.
Source: http://blogs.msmvps.com/peterritchie/2007/04/26/thread-sleep-is-a-sign-of-a-poorly-designed-program/
This doesn't answer your direct question, but it does help address an XY Problem component of your question:
It looks like you're listening for object state changes by polling: by constantly testing an object to see what its state is and whether it's changed, and this is a bad idea, especially when coding for an event-driven GUI. Much better to use an observer pattern and be notified of state changes when or if they occur. That is how the Swing GUI library itself was written, and you should strongly consider emulating this.
Some ways to be notified of changes are to use component event listeners which can listen for changes to Swing components, such as ActionListeners, ChangeListeners, ItemListeners, and the like. Another way when listening to non Swing component items is to use SwingPropertyChangeSupport and PropertyChangeListeners and in this way to create "bound" properties of your class. This is often used for non-GUI model classes.

Make something wait without using Thread.sleep()?

I am trying to make an intro to a game with some strings that I want one to wait for another to pop up, and I don't directly want to use Thread.sleep() for it to wait, because I am not sure if that is the best option. Is there any other way to make something wait than making the thread sleep, or will I just have to make the thread sleep?
If this is a game you shouldn't use sleeps or timers.
Typically games have their own internal clock mechanism. This means you will try to render the frames as fast as possible. Your OnRender method will be invoked with the current time of the game. You can use this to determine if enough time has passed to go to the next screen.
This means you will be given a point in time A in frame 1. You'll be given the Delta or another point in time B in frame 2. You can determine how much time has passed by using the delta or calculating the delta yourself. This is a very efficient mechanism for timing situations and worked quite well when games were single threaded. The idea of any program is to never block for anything.
The reasons things typically block is due to I/O such as reading from disk, the network or putting data on the GPU. In your situation you can do everything without blocking.
Here is a decent page on this https://gamedev.stackexchange.com/questions/1589/fixed-time-step-vs-variable-time-step
There's a standard mechanism for this: Object.wait() and Object.notify() (with their overloads / variants). You simply wait for some event to occur in one thread, and some other thread is responsible for notifying you (or everyone, in case of notifyAll) of that occurrence.
You can also make use of the new Condition mechanism introduced in java.util.concurrent.
If you're making this in a game, why not try using something like Actions in libgdx? You just chain different actors together. Whenever a property like visibility or position reaches the value you want, you trigger the next action. Properties conditions are checked during each update loop of your game.
Or if its a swing app, use a timer to check these properties.
long t1=0,t2=0;
long nanoWaitTime=10000; //to wait at least 10000 nano-seconds
t1=System.nanoTime();
//start waiting
long count=0;
boolean releaseCpuResources=true;
while(Math.abs(t2-t1)<nanoWaitTime)
{
t2=System.nanoTime(); //needs maybe 1000 cycles of cpu to get this value.
//so this is like busy-wait
//and minimum step may be 1 micro-seconds or more
if(releaseCpuResources)
{
count++;
if(count>1000)Thread.sleep(1);//after too many iterations, cpu gets overwhelmed
//so Thread.sleep makes it better for large waiting
//times
//but precision is lost. Like uncertainity principle
//but in a quantized fashion
}
}
// here continue to work after waiting
The resolution or precision may not be what you want in for all cpus.

Pause/Resume arbitrary computation in thread

I'm making a programming game where the player can program their allies' behavior. The player writes the body of the decide() function for a given ally, which can be filled out with any java code but has to return an action. I would like to give each ally a set, restricted amount of computation per tick so 1) adding more entities doesn't slow down the game too much, and 2) The time an entity spends computing is reflected in game, so if an ally spends more time "thinking" it will act less often. My inspiration for how this should work is Battlecode, which gives units a set amount of bytecode per turn, then just pauses the computation and makes the programmer deal with noticing when things have changed.
My question is how I can pause and resume an entity which is executing the decision function in a thread. I understand the 'proper' way to do this is to set a flag telling the thread to pause and have it check occasionally, but since I can't force the player to check for a flag within the decide() function, I'm not sure how to pause the thread. The entities are only looking at a fixed representation of the world and just have to return an enum value, so I don't think they should have locks on anything, but I'm hoping there's a better way to do this than using the deprecated thread pausing methods. I'm open to changing how the player has to write code, but I can't think of a way to do it while still hiding the pause flag checks from the user without making writing the decision loop confusing and onerous. There must be some way to do this, since Battlecode does it, but I'm at a loss searching online for details as to how.
If you want to 'pause' the current thread, java.util.concurrent.locks.LockSupport may helps you. If you want to pause other threads, I thinks it's not in the scope of java design, you can only interrupt another thread, or set a flag, not pause.
You can't "pause a thread", and you can't expect players to abide by your request to "play nice" and check for flags etc. You can interrupt another thread, but the code running in the thread can easily recover from this. So, you need a way for the controlling thread to retain control.
Instead of worrying about what threads are doing, you could:
give the player threads a maximum time to return the action, and if they don't return in time, execute a "default action"
keep a record of how much time they spent calculating and call them more often is they use less time etc
Most of these types of concerns are catered for by java.util.concurrent library. Check out:
ExecutorService
Executors for creating handy instances of ExecutorService
Callable for what the players will implement
Future for getting the result, especially Future.get(timeout) for limiting the time the thread has to return a result

How to get threads with loops running concurrently to work with Thread.yield()?

I have the following situation. I have an application that runs mostly on one thread. It has grown large, so I would like to run a watchdog thread that gets called whenever the main thread changes into a different block of code / method / class so I can see there is "movement" in the code. If the watchdog gets called by the same area for more than a second or a few, it shall set a volatile boolean that the main thread reads at the next checkpoint and terminate / restart.
Now the problem is getting either of the threads to run somewhat at the same time. As soon as the main thread is running, it will not let the watchdog timer count properly. I was therefore thinking of yielding every time it calls the watchdog (so it could calculate time passed and set the value) but to no avail. Using Thread.sleep(1) instead of Thread.yield() works. But I don't want to have several areas of code just wasting calculation time, I am sure I am not doing it the way it is meant to be used.
Here a very simple example of how I would use Thread.yield(). I do not understand why the Threads here will not switch (they do, after a "long" and largely unpredictable time). Please give me an advice on how to make this simple example output ONE and TWO after each other. Like written before, if I switch yield() with sleep(1), it will work just like I'd need it to (in spite of waiting senselessly).
Runnable run1 = new Runnable(){
public void run(){
while(true){
System.out.println("ONE");
Thread.yield();
}
}
};
Runnable run2 = new Runnable(){
public void run(){
while(true){
System.out.println("TWO");
Thread.yield();
}
}
};
Thread tr1 = new Thread(run1);
Thread tr2 = new Thread(run2);
tr1.start();
tr2.start();
Thread.yield()
This static method is essentially used to notify the system that the
current thread is willing to "give up the CPU" for a while. The
general idea is that:
The thread scheduler will select a different thread to run instead of
the current one.
However, the details of how yielding is implemented by the thread
scheduler differ from platform to platform. In general, you shouldn't
rely on it behaving in a particular way. Things that differ include:
when, after yielding, the thread will get an opportunity to run again;
whether or not the thread foregoes its remaining quantum.
The take away is this behavior is pretty much optional and not guaranteed to actually do anything deterministically.
What you are trying to do is serialize the output of two threads in your example and synchronize the output in your stated problem ( which is a different problem ), and that will require some sort of lock or mutex to block the second thread until the first thread is done, which kind of defeats the point of concurrency which is usually the reason threads are used.
Solution
What you really want is a shared piece of data for a flag status that the second thread can react to the first thread changing. Preferably and event driven message passing pattern would be even easier to implement in a concurrently safe manner.
The second thread would be spawned by the first thread and a method called on it to increment the counter for which block it is in, you would just use pure message passing and pass in a state flag Enum or some other notification of a state change.
What you don't want to do is do any kind of polling. Make it event driven and just have the second thread running always and checking the state of its instance variable that gets set by the parent thread.
I do not understand why the Threads here will not switch (they do, after a "long" and largely unpredictable time). Please give me an advice on how to make this simple example output ONE and TWO after each other. Like written before, if I switch yield() with sleep(1), it will work just like I'd need it to (in spite of waiting senselessly).
I think this is more about the difference between ~1000 println calls in a second (when you use sleep(1)) and many, many more without the sleep. I think the Thread is actually yielding but it may be that it is on a multiple processor box so the yield is effectively a no-op.
So what you are seeing is purely a race condition high volume blast to System.out. If you ran this for a minute with the results going to a file I think you'd see a similar number of "ONE" and "TWO" messages in the output. Even if you removed the yield() you would see this behavior.
I just ran a quick trial with your code sending the output to /tmp/x. The program with yield() ran for 5 seconds, generated 1.9m/483k lines, with the output sort | uniq -c of:
243152 ONE
240409 TWO
This means that each thread is generating upwards of 40,000 lines/second. Then I removed the yield() statements and I got just about the same results with different counts of lines like you'd expect with the race conditions -- but the same order of magnitude.

Categories