I've been reading about AsyncTasks and Hanlders and Loopers but I still can't figure out where I'm going wrong in my code. I'm trying to run code that will look over a Tic Tac Toe grid and determine the best move for the computer. I want this code to run in the background 'cause it can take some time and then I can update the UI level with a textbox that says something like "I'm Thinking". I've tried this a bunch of different ways, none with success.
private class PostTask extends AsyncTask<String, Integer, String> {
private Board _b;
private Welcome.Player _opp;
private int _depth;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
protected void SetVars(Board b, Player p, int depth){
_b = b;
_opp = p;
_depth = depth;
}
#Override
protected String doInBackground(String... params) {
Looper.prepare();
try{
_bestMove = _b.GetBestMove(_opp,_depth);
}
catch(Exception err){
_bestMove = -1;
}
return "All done";
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if(_bestMove == -1){
TextView tv = (TextView) findViewById(R.id.tv_Score);
tv.setText("Had and error, couldn't make a move.");
}
FollowUpComputerMove(this);
}
The above code will work for exactly 5 moves and then it crashes. When I watch in the debugger I see new theads being created named Thread<#> AsyncTask #1. Once I get to five of those AsyncTasks it goes back to try and grab the first AsyncTask and crashes. When it crashes I'm shown the ThreadPoolExecutor.class file.
I've also read that I shouldn't be using both the AsyncTask and the Looper objects together so I've tried taking the Loooper.prepare() statement out, but then my AsyncTask fails immediately with the error message:
Can't create handler inside thread that has not called Looper.prepare() - AsyncTask inside a dialog
I've read repeatedly that you shouldn't be trying to update the UI from an AsyncTask and that often the above error is because of that, but GetBestMove isn't updating the UI thread. When I trace through to see where the error comes, it fails when calling a constructor saying it can't find the class.
Can anyone point me in the right direction? My end goal is to use one main thread and only one background thread, and just keep re-using the background thread whenever the computer needs to make a move. I know that the recursive method GetBestMove works when I run this program in a single-thread manner. But the screen freezes for too long on some moves as the method is being run. Thank you so much.
-NifflerX
Apologies for answering my own question, but the issue I was facing had nothing to do with recursion. The class I was calling was extending the class Activity, and while trying to call that from an AsyncTask the program was erroring out. When I removed the extends Activity from the class definition it started working again. Sorry for the post.
-NifflerX
Related
tl:dr at the bottom. I am taking a Java course on Udemy and our instructor is demonstrating a situation where background threads can interfere with each other and crash the program. In this case pushing either of the two buttons initiates a method that starts a background Thread, waits, then updates a label. He explains it something along the lines as the threads overwriting each other causing the program to crash with an IllegalStateException. What I don't understand is Threads overwriting each other is not uncommon and just makes the program behave in ways not intended and doesn't usually completely crash the program.
In this case the threads are both trying to change the label to the same String.
Why is this throwing an IllegalStateException instead of just causing the usual interference? After all more than one thread trying to update an object doesn't necessarily crash the program.
tl:dr Why does more than one thread modifying a Label object throw an IllegalStateException in this case but in other multi-threaded programs you just get the usual thread interference? The method of interest is the onButtonClicked() method.
I have tried catching the IllegalStateException to see if I can call Thread.currentThread().getName() but the catch block(both of them actually) seem to get ignored.
public class Controller {
#FXML
private TextField nameField;
#FXML
private Button helloButton;
#FXML
private Button byeButton;
#FXML
private CheckBox ourCheckBox;
#FXML
private Label ourLabel;
#FXML
public void initialize() {
helloButton.setDisable(true);
byeButton.setDisable(true);
}
#FXML
public void onButtonClicked(ActionEvent event) {
if (event.getSource().equals(helloButton)) {
System.out.println("hello, " + nameField.getText());
} else if (event.getSource().equals(byeButton)) {
System.out.println("Bye, " + nameField.getText());
}
Runnable task = new Runnable() {
#Override
public void run() {
try {
Thread.sleep(5000);
ourLabel.setText("We did something");
} catch (InterruptedException e) {
System.out.println("Interuppted Exception " + e.getMessage());
} catch (IllegalStateException e) {
System.out.println("Illegal State Exception: " + e.getMessage() + " "
+ Thread.currentThread().getName());
}
}
};
new Thread(task).start();
if (ourCheckBox.isSelected()) {
nameField.clear();
byeButton.setDisable(true);
helloButton.setDisable(true);
}
}
#FXML
public void handleKeyReleased() {
String text = nameField.getText();
boolean disableButtons = text.isEmpty() || text.trim().isEmpty();
byeButton.setDisable(disableButtons);
helloButton.setDisable(disableButtons);
}
#FXML
public void handleChange() {
System.out.println("The checkbox is " +
(ourCheckBox.isSelected() ? "checked" : "not checked"));
}
}
Updating active scene graph elements (such as label text) in your own threads has the potential to cause a race condition (please read and understand the Software section of the link) in the internal state of the JavaFX system. The results of which are unpredictable and a corruption or ”crash” of the JavaFX system cannot be ruled out. Perhaps nothing bad will happen, but perhaps something bad will.
Some calls to JavaFX APIs will detect when potential race condition may occur (when they are being invoked by a thread which is not the JavaFX thread), and fail fast by throwing an IllegalStateException. Other JavaFX APIs may not bother to check the calling thread and may not throw an IllegalStateException, thus allowing the potential race condition to occur. Either way, the users calling code is wrong, it should not be trying to modify the active scene graph off of the JavaFX application thread.
JavaFX code which manipulates the active scene graph (elements or properties of elements currently being displayed in a rendered scene) is only ever expected to occur on a single thread (the JavaFX application thread). In that way a race condition cannot occur.
If you want to feedback information from another thread to the UI, then you can either use the Platform.runLater API, which will execute a piece of code at some time in the future on the JavaFX thread, or make use of utilities in the javafx.concurrent package.
My C# app has lots of forms to perform various tasks. To keep things simple, I have a static class FormsCollection where the instances of each of the other forms are kept, so that they are shown and hidden from one place.
Now i was getting that classic debug time "Cross-thread" error. I tried to fix it the following way:
public class FormsCollection : Control // inherited from Control only to be
// able to call "this.Invoke"
{
public delegate void ShowFormDelegate(Form form);
public static Main mainForm;
// and many other forms...
public void ShowForm(Form form)
{
if (form.InvokeRequired)
{
ShowFormDelegate delegateFunc = new ShowFormDelegate(ShowForm);
this.Invoke(delegateFunc, new object[] { form });
}
else
{
previousForm = currentForm;
currentForm.Hide();
currentForm = form;
currentForm.Show();
}
}
}
Inside the user/caller forms, i simply make an object of FormsCollection and call the ShowForm method (almost a 100 such calls):
FormsCollection f = new FormsCollection();
f.ShowForm(FormsCollection.mainForm);
And after all this ordeal, what i get is that the same error appears at the very same spot as before! What an irony! :)
What am i doing wrong? Please help me out....
I got extremely hard-to-find answer to this problem from this slightly irrelevant page. Following is the updated code for any struggling programmers looking for a work around to this problem:
public void Show(Form nextForm)
{
Thread thread = new Thread(
new ThreadStart(() =>
{
PreviousForm.BeginInvoke(
new Action(() =>
{
PreviousForm = CurrentForm;
CurrentForm = nextForm;
PreviousForm.Hide();
CurrentForm.Show();
}
));
}
));
thread.Start();
}
This seems to have resolved the cross-thread problem that i was facing despite several work-arounds. It is working as yet without raising any exceptions and I have tested almost all the scenarios of my app going back and forth from form to form.
I'd like to do the following without making the variable gui final:
public class MainClass
{
GUIClass gui;
Runnable r = new Runnable()
{
public void run()
{
// this won't work!
gui = new GUIClass();
}
};
SwingUtilities.invokeLater(r);
Controller c = new Controller(gui);
}
How can I achieve that? I want to construct the gui via the EDT. At the same time I want to assign that new instance to the variable gui. But this won't work without making gui final. I don't want to use final because it's not possible in my context. Anyone any idea how this could be solved? The code above is of course executed within the main method. But for some reasons I couldn't post it here as an error occured.
For all those who should be interested in this issue someday, here's the solution:
I made a mistake. Actually you should differentiate between constructing the GUI-Object and making it visible. So here is the way to do that:
public class MainClass
{
final GUIClass gui = new GUIClass();
Runnable r = new Runnable()
{
public void run()
{
gui.pack();
gui.setVisible(true);
}
};
SwingUtilities.invokeLater(r);
Controller c = new Controller(gui);
}
In a multi form .NetCF 3.5 application I'm trying create the forms in the background while the user is occupied with the previous form.
We're using Orientation Aware Control in the project
We use a wrapper class (FormController) (please let me know if I'm using the wrong terminology) to keep static references to the different forms in our application. Since we only want to create them once.
At the moment the Forms are created the first time they are used. But since this is a time consuming operation we'd like to do this in the background while the user
Application.Run(new FormController.StartUI());
class FormController{
private static object lockObj = new object();
private static bool secIsLoaded = false;
private static StartForm startForm = new StartForm();
private static SecForm m_SecForm;
static SecForm FormWorkOrderList
{
get
{
CreateSecForm();
return m_SecForm;
}
}
private static void StartUI(){
startForm.Show();
ThreadStart tsSecForm = CreateSecForm;
Thread trSecForm = new Thread(tsSecForm);
trSecForm.Priority = ThreadPriority.BelowNormal;
trSecForm.IsBackground = true;
trSecForm.Start();
return startForm;
}
private static void CreateSecForm()
{
Monitor.Enter(lockObj);
if(!secIsLoaded){
m_SecForm = new SecForm();
secIsLoaded = true;
}
Monitor.Exit(lockObj);
}
private static void GotoSecForm()
{
SecForm.Show();
StartForm.Hide();
}
When I call GotoSecForm() the program throws an excepton on SecForm.Show() with an exection with hResult: 2146233067 and no other valuable information.
The stacktrace of the exception is:
on Microsoft.AGL.Common.MISC.HandleAr(PAL_ERROR ar)
on System.Windows.Forms.Control.SuspendLayout()
on b..ctor(OrientationAwareControl control)
on Clarius.UI.OrientationAwareControl.ApplyResources(CultureInfo cultureInfo, Boolean skipThis)
on Clarius.UI.OrientationAwareControl.ApplyResources()
on Clarius.UI.OrientationAwareControl.OnLoad(EventArgs e)
on Clarius.UI.OrientationAwareControl.c(Object , EventArgs )
on System.Windows.Forms.Form.OnLoad(EventArgs e)
on System.Windows.Forms.Form._SetVisibleNotify(Boolean fVis)
on System.Windows.Forms.Control.set_Visible(Boolean value)
on System.Windows.Forms.Control.Show()
I'm quite qlueless about what's going wrong here. Can anyone help me out?
Or are there some better ways to load the forms in the background?
Let me know if any more information is needed.
You can't create forms (or safely do any manipulation of controls or forms) in background threads. They need to be created on the same thread that the message pump is running on - its just the way that Windows Forms work.
Creating the form itself shouldn't be in itself an expensive task. My advice would be to perform any expensive computations needed to display the form in a background thread, and then pass the result of those computations back to the main message pump in order to create and display the form itself.
(Half way through writing this I realised that this question is about windows mobile, however I'm 99% sure that the above still applies in this situation)
I have a j2me midlet running on a cell phone. The code works fine, but the issue that comes up is that the program seems to be running more than one instance of itself. I have code at the beginning of the application inside the appStart() method that runs twice when the application starts. During the lifetime of the program, the code can be seen running twice when text is written to the screen.
The code looks like this:
public MyClass()
{
form = new Form("MyProgram");
cmdClose = new Command("EXIT", Command.EXIT, 1);
form.addCommand(cmdClose);
form.setCommandListener(this);
display = Display.getDisplay(this);
display.setCurrent(form);
}
public void startApp()
{
form.append("App starting\n");
// Rest of program
}
I have no idea why the code is being called twice.
I'm coding on the i290.
This is definitely a JVM bug. startApp() should be called only once at startup and can't be called again until pauseApp() is called or you call notifyPaused() yourself.
What I suggest is the following code:
private boolean midletStarted = false;
public void startApp() {
if (!midletStarted) {
midletStarted = true;
//Your code
}
}
This way you can track midlet state changes. But in fact it is better that you don't use this method at all and use constructor instead.
Oh, by the way, I don't think that there are some multiple instances or something like that, this is merely a JVM error.
Maybe you did something that made the runtime call pauseApp() and then when you set the focus to the app the runtime called startApp() again.
Put logging in pauseApp() and see what happens.