Starting Thread after GUI construction - java

I have a program that builds the GUI in the constructor. I need a Thread separate from the EDT to run immediately after the object in question is constructed. Could anyone point me in the right direction?

I need a Thread separate from the EDT
Threads are separate from the EDT so all you do is create a Runnable and then start it.
You only have to worry if the Thread updates any GUI components. If this is the case then you may want to use a SwingWorker. Read the section from the Swing tutorial on Concurrency for more information.

What you want to use is a SwingWorker<T,V>. In the doInBackground method, open the connection and start fetching data. When you have enough data to update the gui, call the publish method. Implement the process method to update the gui with the new data from publish, and finally, implement the done method to notify the user when you're finished fetching data.
The Swing Worker is a generic, so when you construct it you need to provide two types: T and V. V is the type for the data passed between publish and process methods and T is the type returned by doInBackground and passed to done.

build your GUI an open a new window inside a new Runnable invoked called by: SwingUtilities.invokeLater

you have two choises
1) wrap Thread into Runnable as demonstrated here
2) I am not very satisfy with plain SwingExecutor, then I use for that Executor and SwingWorker, monitored by PropertyChangeListener, example here,
please carrefully with number of threads started by Executor. Executor doesn't care if SwingWorker ends or not and there still exists Bug where is pretty possible to overload maximum (somewhere in API) simultaneous jobs live by Executor in same time.
by this reason is there possible implements PropertyChangeListener

Related

Updating a view from parallel threads results

I have two threads in my data model layer that run in "parallel" and both compute some values. I have an mvc pattern setup so my data model has two arrays, each responsible for the values generated from each of my threads. How can i tell my view that my arrays have new data without blocking on the main UI?
My threads are running on a timer ever x seconds and generate one integer each. Each of these needs to be added to an array and, when added, the view should get a notification via the observer pattern to update the screen according to the two arrays' updated values. This should happen without ever blocking on the main ui thread. So i cant really do while(true) or set a futureValue for each thread as that would make my ui wait until the threads are done. What can i do?
You will always:
Extend the array class that contains the results and overwrite the add method
Put in the add at the end the code to inform UI-Thread
To synchronize the updates, you can use a ExecutorService with just one Thread, that you get with Executors.newSingleThreadExecutor(). In that you submit() the code to inform UI-Thread.
Your execution should be part of a WorkerThread and be handled in doInBackground
In the done() method you update the User interface (done() is executed on Swing's event dispatch thread)
See here for more information on Threads and Swing
This seems like a pretty complex approach. Here is mine:
Create a blocking queue
Get rid of the arrays and have each thread put their results in the queue
Start a worker thread that waits for items in the queue
Use SwingUtilities.invokeLater() in the worker thread to update the UI.

Is there a way to set the priority of the background thread used by a SwingWorker?

In Java is there a way to set the priority for the thread that will be calling the doInBackground() method of a SwingWorker object?
In the Thread API there is a setPriority() method. The SwingWorker.execute() method schedules the swingworker for execution on a worker thread. I would like to have access to that worker thread to set it's priority.
From my understanding this worker thread comes from a default worker thread pool. Would the only way to handle this is to use my own executor?
The JDK7 SwingWorker javadoc hints that the designers did not intend for users to directly interact with or alter the background threads:
... the exact strategy of choosing a thread for any particular SwingWorker is unspecified and should not be relied on.
The implementation of SwingWorker.getWorkersExecutorService() seems to reinforce this idea as they've implemented it in a way that is not easily changed.
SwingWorker is a boilerplate solution to the typical case and you don't have a typical case. I'd suggest you write the code to handle running the background tasks instead of trying to hack SwingWorker to do what you want. That way whoever gets to maintain your code in the future (perhaps even yourself!) won't be left wondering why SwingWorker isn't behaving as expected.
The only way I can think to do this is to have the execute method grab the current thread using Thread.currentThread(). You can then set the priority of this thread (provided the caller is allowed to).
As the SwingWorker is a Runnable, you can submit it to any java.util.concurrent.ExecutorService

Java Swing application: how to get data from the GUI thread to another thread?

In my Java application with a Swing GUI, I would like to achieve the following.
There is a non-GUI thread running, performing some work. At one point, this thread needs input from the user before it can continue. Then, I would like to make some changes to the GUI, await a specific GUI action (like the user pressing the OK button), get the entered data from the GUI to the non-GUI thread, and let it continue with the computation.
Looking around, I have found a lot of information about how to initiate the execution of a (long running) task from the Swing GUI thread on another thread, but nothing on my problem.
SwingUtilites.invokeAndWait sounds like it does the job, but first, it takes a Runnable argument instead of a Callable, so there is no straightforward way to return a result, and second, it does not solve the problem of waiting for a certain GUI event.
I realize I could make up my own solution using e.g. a CountDownLatch, but to me, the problem seems frequent enough for there to be a standard solution.
So, my questions are: Is this really a frequent problem, and if yes, is there a solution in the standard library / libraries? If there is no standard solution, how would you solve it? If this problem doesn't occur often, why not?
Kicking off the GUI changes is easy, so I assume you're only asking about getting data back to the worker thread.
First, create a Blocking Queue. Have the worker thread call take() on the queue, and it will block. In GUI space, once the user enters valid input, put it on the queue with offer() and the worker thread will receive the data and can continue.
I think, you can use ExecutorService where you can also track progress of your task through Future interface.
java.awt.EventQueue.invokeLater works nicely for running code on the AWT EDT. Propbably best to copy mutable data or better use immutable data. Locks are possible, but a bit dicey.
If you other thread is an event dispatch loop, you could implement something like invokeLater for your thread (but don't make it static!). Probably use it behind some interface that makes sense to the behaviour of the thread - so it's real operations rather than run which is specified as doing anything it pleases. If your thread is going to block, then a BlockQueue is fine, but don't block from the AWT EDT.
java.awt.EventQueue.invokeAndWait is like using a lock. Probably you are going to use another lock. Or perhaps a lock like invokeAndWait on you own thread. If you don't, AWT uses a lock anyway. So, uncontrolled nested locks, that probably means deadlock. Don't use invokeAndWait!
final bool result = doSomething();
SwingUtilities.invokeLater( new Runnable(){
//Runnable method implementation.
//use result in your method like local var.
});
Make sure that your shared data is synchronized use lock objects.
If you need to pass arguments to Runnable just make your local variables final,
and use them in run method.

Swing/SwingWorker Beginer's question

I am trying to implement a GUI in java but I am beginner in swing. I want to make something clear. I read that in order to keep the GUI responsive I should use the SwingWorker class to do the task in a separate thread. Ok so far.
No I have a model with around 15 methods that are remote methods. Each method returns different object type as a result than the others.
In my view the user presses a button and the appropriate method in the model is called. Without using the swingworker the GUI froze. My question is, am I supposed to create 15 subclasses of Swingworker threads and create a NEW instance of each as needed according to user's actions? Is my understanding correct? Is there a standard way for this or what I say is a correct approach?
Thanks!
Have a look at this: Simple Background Tasks.
It seems you have two concerns. Firstly, regarding the amount of code required when using SwingWorker: you do need to create a subclass of SwingWorker for each action, but that doesn't mean they need to be top-level, named classes, or in their own files. They can be anonymous classes, as shown in the article, so that the code is within your GUI's event-handling code.
Secondly, regarding instantiation of SwingWorker objects: you can't reuse a SwingWorker, but since the jobs are being executed as a result of user activity (e.g. clicking a button), you shouldn't encounter any performance problems with instantiating new objects each time.
By all means, SwingWorkers get the job done. In my experience, I haven't liked using the SwingWorkers for just one little job. I prefer to spawn off a thread, and have that thread ask the EventDispatch thread to update the GUI. Only the EventDispatch thread should update the UI, though there are a few exceptions.
I would suggest reading about threads in threads in Swing.
Though threading can get heavy, and maybe this solution would not work for you in all cases, if a seperate thread needs to spark a change in GUI, use something like,
java.awt.EventQueue.invokeLater(new Runnable()
{
public void run()
{
// this codes runs on the event dispatch thread
// update the ui here.
}
});

Java (Android) threads - repeating task at intervals, and accessing values

I'm programming on Android, but I guess this is a general Java 101 question...
I want myMethod() to run every X ms without blocking the UI - it should be possible to start and stop this thread. The value of X milliseconds will change whilst it's being run. myMethod() needs read access to an array which is manipulated by the UI.
How can I do this? As the interval changes I can't use schedule(); so is this a valid case for sleep(int X)? If I do start a new thread (runnable or extending Thread) in a new class, how can I read the UI class's array? (does something like parent.getarray() exist?). What's the best way to tackle this?
ScheduledThreadPoolExecutor class gives you scheduling functionality. It has some advantages over java.util.Timer
I don't know Android, but it seems that ScheduledThreadPoolExecutor is available on Android as well.
Using STPE is simple: you create your Runnable or Callable instance, and pass it to your executor via schedule method together with scheduling information (how often it is called, what is beginning delay).
To access array from your UI thread, you need to use some kind of synchronization. Take a look at AtomicReferenceArray, AtomicLongArray or AtomicIntegerArray if they can help you (they give you atomic access to array elements without any other synchronization, although you better make your array variables final). Other option is to put all reads and writes to array into synchronized blocks. Another possibility is to use CopyOnWriteArrayList. If you need to also update UI from your background task, you need to wrap your updating code into another Runnable and pass it to UI thread. Best option really depends on what exactly you're doing.
You could create a java.util.Timer object keeping a TimerTask object around. That way you could simply schedule the Timer each time for the desired X to act on the TimerTask
http://developer.android.com/reference/java/util/Timer.html
http://developer.android.com/reference/java/util/TimerTask.html

Categories