Identifying Swing Threads for displaying frequent data input in Java - java

For my current application, I am struggling with identifying the Swing threads in my application. With Swing threads I mean:
Initial threads
The event dispatch thread
Worker threads
My application:
simple user interface which is supposed to display data received on a socket
the data is described by many model classes
the received data is XML which is parsed and the model objects are instantiated
the user interface is supposed to display the received data
these data is updated very frequently, which means the XML messages are short, but there are many of them
to put it into context: I am programming a Java profiler.
I have read the Swing tutorial so far, so here are my guesses and questions:
The background task is the server socket, respectively the background tasks are the number of opened connections on which the application receives data.
The tasks have no final result, so I guess the SwingWorker<T,S> should only define the generic type for the Interim Result? For every parsed XML I would make a call to publish. But how do I distinguish which data I have received? Maybe the XML data contains only enough information to build a class A or maybe the data contains enough information to build class A and class B, but how do I wrap both into one Interim Result? A wrapper class?
The process() method invokes changes to make it visible to the user interface, doesn't it? I don't see how this works. Where do I launch my tasks? Is it in order to invoke the SwingWorker.execute() in the JFrame constructor?
Should the XML Reader be the Task or should each Thread which handles an incoming connection be the task?

In the context you describe, I am not sure I would use SwingWorker.
My basic idea would be:
from your main(), start several threads for serving sockets (standard Thread API)
when one such socket thread gets some input, it parses the XML right away (as you describe it, parsing should be very fast, hence I don't think you would need to start a new thread just for that)
once the XML is parsed, the socket thread creates some "result object" to be displayed, declare this object in a final variable, and call SwingUtilities.invokeLater() to display this result in your UI
Another alternative that I have used successfully in the past would be to use an EventBus that would take care of callingthe UI update method in the EDT, your socket threads would send the "result object" to that EventBus.
About SwingWorker use, I would say the main use is when the end user starts an action (e.g. by clicking a button or a menu item) and this action is long and should be processed in background, the background processing method would then have to feed back information to the UI.

Related

How can I make multiple Jframes consume data from the same Thread in Java?

I have a program that must output the data of a weighting scale. It uses a thread to read continually data from the rs232 source and must output the data graphically. The user can open and close as many Jframes as it wishes and all must show the same data that is read from the rs232 in a JTextArea. How can I approach this?
Thank you very much in advance.
There are a number of ways you might approach this problem
The user can open and close as many Jframes as it wishes and all must show the same data that is read from the rs232
This raises the question if you're only interested in the real time results or the historical results. For argument sake, I'm only going to focus on the real time results.
Basically you need to start with a class which is responsible for actually reading the data from the port. This class should do only two things:
Read the data
Generate events when new data is read
Why? Because then any additional functionality you want to implement (like writing the data to a database or caching the results for some reason) can be added later, simply by monitoring the events that are generated.
Next, you need to define a interface which describes the contract that observers will implement in order to be able to receive events
public interface ScaleDataSourceListener {
public void scaleDataUpdated(ScaleDataSourceEvent evt);
}
You could also add connection events (connect/disconnect) or other events which might be important, but I've kept it simple.
The ScaleDataSourceEvent would be a simple interface which described the data of the event
public interface ScaleDataSourceEvent {
public ScaleDataSource getSource();
public double data();
}
for example (I like interfaces, they describe the expected contract, define the responsibility and limit what other people can do when they receive an instance of an object implementing the interface, but that's me)
Your data source would then allow observers to register themselves to be notified about events generated by it...
public interface ScaleDataSource ... {
//...
public void addDataSourceListener(ScaleDataSourceListener listener);
public void removeDataSourceListener(ScaleDataSourceListener listener);
}
(I'm assuming the data source will be able to do other stuff, but I've left that up to you to fill in, again, I prefer interfaces where possible, that's not a design restriction on your part ;))
So, when data is read from the port, it would generate a new event and notify all the registered listeners.
Now, Swing is not thread safe, what this means is, you shouldn't make updates to the UI from any thread other then the Event Dispatching Thread.
In your case, probably the simplest solution would be to simply use SwingUtilities.invokeLater to move from the data sources thread context to the EDT.
Basically, this is a simple Observer Pattern
There are a lot of other considerations you need to think about as well. Ie, are the frames been opened within the same process as the data source, or does the data source operate within it's own, seperate process. This complicates the process, as you'll need some kind of IPC system, maybe using sockets, but the overriding design is the same.
What happens if the data source is reading data faster then you can generate events? You might need some kind of queue, where the data source simply dumps the data to the queue and you have some kind of dispatcher (on another thread) reading it and dispatching events.
There are number implementations of blocking queues which provide a level of thread safety, have a look through concurrency APIs for more details.
... as some ideas ;)
first, create a frame class extends JFrame, and create a method to receive data from rs232. Then every object of this class can get data using that method.
u can create one frame by creating one object of the class.

Android - What is a Handler Message?

I'm talking about this class.
The main documentation states:
Defines a message containing a description and arbitrary data object
that can be sent to a Handler. This object contains two extra int
fields and an extra object field that allow you to not do allocations
in many cases.
So I would assume that it is some kind of communication between
different threads, maybe a Bundle?
There are also a few snippets in the main documentation. But I
can't see how are they built and what is their structure.
Why to use them instead of using SharedPreferences or maybe a Singleton class? Testing?
I would love to see a little and compact example on when and how to use them.
So I would assume that it is some kind of communication between different threads
You can attach a Handler to the main application thread (a.k.a., UI thread), and you can create separate HandlerThread instances for other threads with associated Handler instances.
One thread can send a Message, via a Handler, where the Handler will process the Message on its own thread, in the handleMessage() method. For example, a regular background Thread could package the results of its work (e.g., downloaded data) into a Message, and give that to a Handler attached to the main application thread. That Handler will get the Message in handleMessage(), called on the main application thread, and can then update the UI safely using the data from the background thread.
This is a very low-level means of inter-thread communication in Android. More often, you are better served using something a bit higher-order, like an event bus.
Why to use them instead of using SharedPreferences
SharedPreferences are for data storage, not inter-thread communication.
or maybe a Singleton class?
While a singleton can provide a central point of data, on its own, it does not provide any sort of inter-thread communication.
I would love to see a little and compact example on when and how to use them.
For 99% of Android developers, the answer is: don't use them. Use something that is built on top of Handler and Message, such as:
AsyncTask
LocalBroadcastManager
Square's Otto
greenrobot's EventBus
etc.
A Thread can have one handler and one messageQueue only, a message is some arbitrary data that is handled by the handler whom put on it's messageQueue, the messageQueue loop every message and process them until it has no more message, all data are versatile and executed asap, no need to save it on HDD, it's low level code you dont deal with it often

Multithreading with swing

I have a question about the use of threads in a gui application. Say (as a simplistic example) i have a swing application with a series of images. I have two threads i want to run that fetch an image of a parent respectively. (So for a given number of students, get a mother image and a father image from each server endpoint). The returned image of the father and the mother is then appended on to the image on screen so i have a series of images with a mother, father, mother, father for multiple students.
How can i schedule this in a multithreaded environment? Each call to get a mother or father image has to be in parallel and not block the displaying of the images on screen. Does the image displayed on the screen refresh after each thread returns an image? How will this be structured?
Start with Concurrency in Swing.
The absolute simplest approach might be to use a SwingWorker that has a list of items it needs to look up and allow it to process the list.
The problem with this is it will only run each request one at the other, making it a little slower then other options. The benefit of this is that it provides easy functionality to re-sync with the Event Dispatching Thread so that you can notify the UI or make changes to it safely.
Another option might be to use Executors, in particular a Thread Pool implementation.
This allows you to submit a number of tasks that should be executed at some time in the future, but allows you to control the number of threads that the process can use at any one time.
The drawback is that you become responsible for syncing the changes back to the UI yourself when you want to update the UI, using SwingUtilities.invokeLater
Now. You "could" use both.
Basically you would need to setup some kind of "request" class that would allow you to pass the relevant information to, for example, the "mother" and "father" servers, the original image and possibly some kind of callback interface that would tell you when the final image had being rendered.
The requester would build some kind of Runnable or Callable which would wrap a SwingWorker.
When executed, this "request task" would start the SwingWorker, allowing it to fetch the images, merge them and publish the results, which would notify the callback interface. The "request task" would then simply wait until SwingWorker#get returns before exiting.
As an idea...

Events or Handlers? Invoking methods from a thread

Consider a simple Android application: there are two TabActivities and a thread in the background getting integer values from a server. If the number is even, it must be displayed in the first tab otherwise in the second. Obviously I will be doing something more complicated, but this is the basic pattern. How do I go about doing this? I have been scratching my head for about a day now and here are things I have come across:
Use of EventHandlers. The two TabActivities register for listening for my_events and when a value is received by the thread, it 'throws my_event' and then specific methods in both these activites are called and the value is passed.
The use of Handlers.
I have not used both of these concepts before and I would like to know which might be the better/correct route to take. Further, any more tips along the chosen route will be appreciated. Also, should this thread be run from a service class?
When you create your thread just pass the objects of your tabs into it, then in your execution you can easily put the text you want into tabs.
Possibly you want to look at using an AysncTask. If you do this you want to insert the values into the appropriate tab in the onProgressUpdate() method. Since the arguments passed to this method may not actually be able to represent the incoming data sufficiently you'll just want to put the new data somewhere that it can be accessed from the onProgressUpdate() method, probably in a member variable. Keep in mind that access to this member variable probably needs to be synchronized because code in onProgressUpdate is running on the application's main thread, while code in doInBackground is running on a background thread so code in these methods will be running concurrently.
AsyncTask uses Handlers transparently for you, but you could use raw Handlers if you wanted. The basic things you need to keep in mind are
You can/should only update the UI from the main application thread
Code in a Handler will always run on the Thread that created the Handler
Handlers must be created on a Thread that has a Looper (the main Thread has a Looper)
Be careful if creating the Handler as an anonymous inner class or handing it a reference to a Context since this creates the potential for a memory leak
Possibly the Thread should be invoked by a Service, but if the Thread only needs to exist when there is a UI for it to update there may be little point to this.

Implementing java FixedTreadPool status listener

It's about an application which is supposed to process (VAD, Loudness, Clipping) a lot of soundfiles (e.g. 100k). At this time, I create as many worker threads (callables) as I can put into memory, and then run all with a threadPool.invokeAll(), write results to file system, unload processed files and continue at step 1. Due to the fact it's an app with a GUI, i don't want to user to feel like the app "is not responding" while processing all soundfiles. (which it does at this time cause invokeAll is blocking). I'm not sure what is a "good" way to fix this. It shall not be possible for the user to do other things while processing, but I'd like to show a progress bar like "10 of 100000 soundfiles are done". So how do I get there? Do I have to create a "watcher thread", so that every worker hold a callback on it? I'm quite new to multi threading, and don't get the idea of such a mechanism.
If you need to know: I'm using SWT/JFace.
You could use an ExecutorCompletionService for this purpose; if you submit each of the Callable tasks in a loop, you can then call the take method of the completion service - receiving tasks one at a time as they finish. Every time you take a task, you can update your GUI.
As another option, you could implement your own ExecutorService that is also an Observable, allowing the publication of updates to subscribing Observers whenever a task is completed.
You should have a look at SwingWorker. It's a good class for doing lengthy operations whilst reporting back progress to the gui and maintaining a responsive gui.
Using a Swing Worker Thread provides some good information.

Categories

Resources