I really like the javax.swing.SwingWorker, it's such a easy way to handle Multithreading.
Now I have a server-application without any GUI and want to use something like the SwingWorker, with the process(), done(), cancel(), etc...-methods.
I know I could just use the swing worker and probably have no problem, but still the swing worker obviously is intended to be used together with a swing-application.
So is there anything like the swing worker that is intended to be used in more general cases, but pretty much does the same?
Or if not so, what are the disadvantages of using swing worker and not working with Swing?
What comes to my mind is bad code-style and the done() and process() - method being executed in the EDT.
Most server frameworks expect that you will not attempt to manage threads by yourself. This is usually due to the way they are implemented (resources sur as transactions, security principal, loggers...) might be thread locals. Most of the API are outright not thread-safe, for instance a JDBC connection is not.
For instance the J2EE restrictions indicate that you should not create or manage threads.
Related
I recently learnt that Sun's/Oracle's most recent guidelines say that no Swing methods of any Swing objects, including constructors, must be called outside the EDT.
Does the same standard of rigour apply to all "visual" AWT classes too? If not, what ** are ** the rules for them?
later
re Swing and EDT: discussion from 2009.
http://www.velocityreviews.com/forums/t707173-why-does-jdk-1-6-recommend-creating-swing-components-on-the-edt.html
quote:
"Besides actual thread safety and associated issues like visibility and
synchronization, there's I think a software issue. Swing components
often have "listeners" of some type, and these listeners are designed to
execute on the EDT.
Since these listeners are asynchronous and respond to events (like
property changes) it's possible to have these listeners fire as you
construct your GUI. The result is that some listeners are being
executed on the EDT as you are constructing in your main thread, and
some listeners might be running on some other thread as well (because
the listener is confused and fires on the wrong thread). The result is
a huge unpredictable mess."
maybe they don't know what they're talking about... but at the moment I'm taking a "better safe than sorry" approach. Also Potochkin, at http://weblogs.java.net/blog/alexfromsun/archive/2006/02/debugging_swing.html seems to take it as read that we are familiar with the later, stricter rules
Correct synchronization in a multi-threaded Java program hinges on the happens-before relation, summarized in Memory Consistency Properties. AWT Components were intended to be thread safe, synchronizing on a private lock object in java.awt.Component. See the comments for some historical perspective:
private transient Object objectLock = new Object();
While this may prove sufficient for simple programs, more complex programs are required to rely on knowledge of this implementation detail to verify correct synchronization. It's possible, but who wants to settle for a brittle AWT GUI?
Some additional points:
The article cited by #Hovercraft dates to 1998, but it has been updated repeatedly to address such issues as the new memory model mentioned in the usenet thread you cited.
The evolution of javax.swing has been away from GUI API promises, as mentioned here, and toward more flexible concurrent programming tools.
You state:
why AWT? Good question. I am just now rewriting stuff on the basis that all Swing calls must be done in the EDT... if AWT is slightly more permissive this might be of use for some simple GUI purposes...
My reply:
That's bad reasoning. Swing is so much more powerful and flexible that it would be like breaking a puppy's legs before buying it just so you wouldn't have to walk it. Use Swing, follow the threading rules which are hardly likely to be more onerous than AWT, and enjoy. The threading rules make sense and are not hard to follow. Again, this article is a great reference for this.
I am working with a 3rd party proprietary library (no source code) which creates instances of a non thread safe component. Does this mean that I shouldn't use multiple threads to run jobs in parallel? Running each job in it's own JVM crossed my mind but is overkill.
Then I read the article here
http://cscarioni.blogspot.com/2011/09/alternatives-to-threading-in-java-stm.html
Is it recommended to follow that article's advice? What other alternatives exist out there?
Response to Martin James:
Vendor tells me that there is only one thread in which multiple instances of the component exist (Factory pattern to create the component instance) and each instance is independently controllable from it's API.
So does this mean that I can still use multiple threads while controlling each component instances running in one big thread?
No, it does not mean this.
It means that you should care about data protection yourself. One possible way is to synchronize access to that library in code that calls it (your code). Other possible way is using immutable objects (for example make private copy of non-threadsafe data structure every time you want to work with it).
Other way is to design your application that way that the code that works with certain object always run in the same thread. It does not mean that code that is working with other object (even of the same class) cannot run int other thread. So, the system is multi-threaded but no data clashes are created.
'Vendor tells me that there is only one thread in which multiple instances of the componenet exist (Factory pattern to create the component instance) and each instance is independently controllable from it's API.'
That is not exactly 100% clear. What I think it means is:
1) Creation of components is not thread-safe. Maybe they are all stored internally in a non-threadsafe container. Presumably, destruction of the components is not thread-safe either.
2) Once created, the components are 'independently controllable' - this suggests strongly that they are thread-safe.
That's my take on it so far. Maybe your vendor could confirm it, just to be sure, before you proceed any further with a design.
It all depends on what your code is actually doing with the components. For example, ArrayList is not thread safe, but Vector is thread safe. However, if you use an ArrayList inside a thread in a way that is thread safe or thread neutral, it doesn't matter. For example, you can use ArrayLists without any issue in a JavaEE container for web services because each web service call is going to be on its own thread and no one in their right mind would have web service handling threads communicating with each other. In fact, Vectors are very bad in a JavaEE container if you can avoid using them because they're synchronized on most of their methods, which means the container's threads will block until any operation is done.
As AlexR said, you can synchronize things, but the best approach is to really look at your code and figure out if the threads are actually going to be sharing data and state or going off and doing their own thing.
I want to use this Swing snippet to create an image from a text label from a non-Swing based app (a web service written using Play Framework, to be specific).
I've never used Swing, and saw that "it is not thread safe". Does this apply to the minimal code that I'm planning to run? Should I synchronize access to this code?
If I understand the answers about Swing thread-safety correctly, then unless a method explicitally says it's safe, then it isn't ... and the methods I use (specifically BufferedImage.getGraphics() don't seem to have this piece of javadoc). So, unless shown otherwise, I'm going to synchronize.
"Not thread-safe" means that you must not access the same thing from multiple threads at once.
There is nothing wrong with running that code on a background thread, as long as you don't share the objects across threads.
Note that most (non-UI) objects are thread-safe for read-only operation.
EDIT: actually, you can cut out all the Swing related parts in your "Swing snippet" since you really only care about the image manipulation part, which has nothing to do with Swing.
Don't worry about anything: your code is not multi-threaded.
Where it gets complicated with Swing is when you have some actual interface. The interface is run from a special thread (the event-dispatch thread or EDT), which is a different thread from the main thread where you program runs. If you update some value in your main program, you have to be careful with multi-threading issue otherwise your updated value will never show on screen.
Since you are just using some methods from the Swing library without having any EDT it's just like using any method from a normal library.
I usually use the Observer pattern, my colleague at work though has implemented an Observer using Thread intercommunication (using wait and notify/notifyAll).
Should I implement my observers using the pattern or inter-Thread-communication using wait and notify? Are there any good reasons to avoid one approach and always use the other?
I've always gone with the first one, using the pattern, out of convention, and because it seems more expressive (involved identifiers are a good way to express and understand what is communicated and how).
EDIT:
I'm using the pattern in a Swing GUI, he's using the inter-thread solution in an Android application.
In his solution one thread generates data and then calls notify, to wake up another thread that paints the generated data and calls wait after every paint.
His argument for the wait/notify solution is that it creates less threads and even several concurrent calls to notify will cause only 1 paint event, whereas an observer-based solution would call a repaint with every call. He says it's just another valid approach, but doesn't claim he's done it for performance reasons.
My argument is that I would express the communication among objects on the OO design level rather than use a language-specific feature that makes the communication almost invisible. Also, low-level thread communication is hard to master, might be hard to understand by other readers, and should rather be implemented on a higher level, i. e. using a CyclicBarrier. I don't have any sound arguments for one or the other solution, but I was wondering if there are any sound arguments for either one or the other approach (i. e. "This-and-that can happen, if you use this approach, whereas in the other one that's not possible.").
You are comparing apples and oranges. The wait/notify mechanism is used for thread synchronization, and while your colleague may have used it within an Observer/Observable implementation, it is not, in itself the pattern implementation. It simply means it is a multithreaded implementation.
There are many implementations of this pattern, and they are typically tailored to the environment in which you are working. There are event mechanisms built into most UI frameworks/toolkits. JMS for distributed environments, ...
I don't find much use for the generic Observer/Observable classes provided by the JDK, and from experience I haven't found many other developers use them either. Most will use a provided mechanism, if appropriate, or roll their own specific and ultimately more useful implementation if needed.
Since I have done most of my coding in an OSGi environment of late, I have a preference for a variation of observer/observable called the whiteboard pattern. This may or may not be feasible for you, depending on your environment.
You should avoid, or rather refrain from, inter-thread communication in 99.99% of the cases. If there is a real need for a multi threaded solution, you should use a higher level concurrency mechanism such as an ExecutorService or a good concurrency library such as jetlang: http://code.google.com/p/jetlang/.
Difficult. I would normally use Observer / Observable when not explicitly writing a multithreaded application. However, convention in this case might be for you to use his design. Perhaps see if you can abstract it out somehow so that you can replace it with the Observer pattern at a later stage if necessary?
However, I found these two articles which seem to indicate that the Observer/Observable pattern in Java is not ideal and should be avoided.
An inside view of Observer and
The event generator idiom
Re: Requirement to create Swing Object on Event-Dispatch Thread.
I am working on an application, the purpose of which is to monitor and display the condition of various remote embedded servers. I'm pretty new to Java, and my understanding of the requirement with respect to the Swing Objects and the EDT is incomplete.
The main GUI is started on the EDT in the usual fashion as follows,
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
The user may then select one or more menu options corresponding to the one or other of the remote machines. The effect of this is to create a new thread each time as follows
new Thread(new VoterStatus(itemNumber)).start();
which invokes VoterStatus's class "run" method which in turn creates a new window with a JFrame. The new thread, an instance of VoterStatus class, then interrogates (TCP etc) the particular remote specified (itemNumber), collecting various bits of information and displaying them in the JFrame.
There may be any number of such threads corresponding to an instance of VoterStatus, all updating their own windows. There is no sharing of data between these various windows/JFrame/tasks.
This seems to work just fine, but is is safe?
Have I violated the rule about creating Swing components on the EDT?
Would use of the SwingWorker class be beneficial?
I would appreciate any comments from Java programmers more experienced in such matters.
Thanks
Steve
From the section in the Swing tutorial titled The Event Dispatch Thread
Some Swing component methods are labelled "thread safe" in the API specification; these can be safely invoked from any thread. All other Swing component methods must be invoked from the event dispatch thread. Programs that ignore this rule may function correctly most of the time, but are subject to unpredictable errors that are difficult to reproduce.
I always invoke my methods on the EDT so I don't waste time chasing gremlins.
Edit:
I just read another posting which states that the comment "thread safe" has been removed from many methods in the JDK7 API. http://forums.oracle.com/forums/thread.jspa?threadID=2167051. This looks like another reason to make sure all methods that affect the GUI are executed on the EDT.
#camickr has the right of it. Incorrectly synchronized programs may appear to work most of the time, but the result is not reliable. Several related approaches are discussed here. SwingWorker is an especially convenient implementation of the Future interface, as process() runs on the event dispatch thread.
You might be safe, but you can be sure by creating your other UI components in the EDT, just like you did for the main application.
However, I would suggest a different approach. Rather than firing off a new Thread which creates the windows and stuff for each new VoterStatus, create the UI components in the EDT in response to ActionEvents from menus or whatever, and do processing of the network stuff only in a different thread. Then get the results and use the EDT to display them. As you've suggested, a SwingWorker is ideal for this - this is exactly the sort of use it was designed for. This represents a cleaner separation for me, separating the UI stuff from the network stuff as much as possible.
I'm not really answering my own question, but I do want to thank those that responded and ask a follow up question or two.
Rogash commented that if I was only creating the GUI on the EDT, I would be ok, but this doesn't seem quite in accordance with a strict interpretation of the rule?
The additional threads are created in the EDT, but they are still separate threads.
Whilst slightly better separation of the GUI and comms may be desirable, I expect this will add considerable complexity to the main GUI code, since it will have to determine which window originated various events and then update the correct window, not to mention the communication between the various threads and the main GUI thread. Perhaps I am overstating this difficulty (I haven't designed or thought about how to code it yet) but it would seem more complicated. Each of the threads/JFrame already has a couple of JToggleButton arrays (30 elements) causing potential events and 10 or so JTextField arrays with the same number of elements requiring updating.
Of course, if my method is unsafe, I'll have to change it, and that's that!
Actually, I wonder if I might be better off leaving things the way they are, and using a mutex or semaphore to make sure only one thread is accessing Swing methods at a time. There is really no long user actions or any other activity takes a long time, just lots of TCP or UDP packets being received that require the screen display to be updated.
Thanks again
Steve
PS I tried to register on this forum, but I think this discussion will stay with my unregistered persona.