J2ME lcdui: Can I manipulate my GUI in a worker thread? - java

I'm just starting with J2ME and lcdui, and I'm looking at some sample code that calls methods on lcdui objects from a worker thread.
In my experience with desktop GUI toolkits, this is usually forbidden - is lcdui different? Is it really OK to do this?
(I've Googled for an answer to this question but not found anything - a link to a defintive answer in some official documentation would be excellent!)

LCDUI is a bit of a funny one, what you can and can't do often depends on the implementation. I've written apps for BlackBerry that don't have a problem with accessing UI objects from a background thread (except the usual threading problems that you create yourself), but I'm pretty sure some other platforms will forbid this.
If you're concerned about this, or it's causing you issues, you might want to look at using javax.microedition.lcdui.Display.callSerially(Runnable). This executes the given Runnable object in the UI thread (if there is such a thing in LCDUI) and serializes it with other UI events and paint operations. You can read more about it in the J2ME API docs.

Using the javax.microedition.lcdui classes, thread-safety is supposedly one of the goals of the UI classes according to the Concurrency section of this documentation. As Rory indicated, it is entirely possible that different vendors implemented this as more of a "suggestion" rather than a rule.
At one time, I was looking for similar information, but was also unable to find the magic phrasing to offer Google to get good results.
Best of luck!

Related

JavaFX and Swing --- finding a middle ground?

I am so-so with Swing and just starting to learn JavaFX. I went over a few answers on SO with regards to which one to use and I still can not make up my mind.
Is it possible to get the best of both the worlds ??
Like, use JavaFX with I want to give some visually appealing graphics and add some Swing to JavaFX when I want to ?
You can use JavaFX in Swing applications via the JFXPanel control. See the SwingInterOp sample. You can also utilize JavaFX from inside sophisticated Swing based platforms such as NetBeans RCP.
A current limitation of JavaFX/Swing integration is that you can embed JavaFX components in a Swing application, but not Swing components in a JavaFX application. RT-12100 Swing in JavaFX embedding support is currently scheduled for Java 8.
If you have a green field new application to develop, I'd advise choosing one technology or the other and sticking with that or at least keeping the integration points localized and few and far between. Both frameworks are large and take time to learn, plus you will avoid any integration headaches such as needing to take care that Swing processing is done on the Swing Event Dispatch thread and JavaFX processing is done on the JavaFX Application Thread.
JavaFX also integrates with SWT and that integration is currently simpler than the JavaFX/Swing integration (because there is only a single GUI thread to worry about).
Here is a screenshot of JavaFX/Swing interop sample from Oracle:
I went over a few answers on SO with regards to which one to use and I still can not make up my mind.
Rather than doing that, I'd advise picking a small application and implementing it from scratch in Swing and JavaFX and seeing which you prefer. It's time better spent as there is no substitute for hands on experience - then, if you still have questions (hopefully more specific and targeted), come back to StackOverflow to research or ask them.
It depends on your motivation for learning them. If you're looking primarily to boost your CV in the near future and become attractive to businesses, then (for the moment at least) there's many more applications out there written in Swing than JavaFX, purely because the latter is a much newer toolkit.
However, if you're thinking more long term or just want the best tool for the job, personally I find JavaFX to offer more flexibility, be much easier to code in an aesthetically pleasing way, and easier to learn as well (the API behind it is just much nicer.) The only thing against it at the moment is that there's some features that I'd really like to be included, but aren't yet (again, naturally this is what you get by going for the newer toolkit.)
I'd also advise against mixing the two. I'm currently involved in two projects using JavaFX, one entirely JavaFX based and the other a mixture of FX and swing. The latter is much more fiddly to maintain, primarily because of the difference in dispatch threading.
As a previous poster stated, you can use JavaFX in Swing applications now. But since Oracle has declared that JavaFX is the future of the desktop for Java, why not just learn it. I've tried to keep current on both and it's a chore. I'm planning on focusing on JavaFX exclusively in the future -- less chance of confusing myself.
That said, JavaFX still doesn't seem to be a full-fledged member of the JDK, especially if used in conjunction with other languages, like Clojure for example. Depending on the JavaFX version, there are different machinations to go through to pull it into build tools. But that situation is getting better with each release.

In Java, is there something like "DoEvents" from VB6

I'm coming from VB6 and I'm new to Java. In VB6, DoEvents gives up the processor and allows it to process other threads. Is there a similar thing in Java? How do I use it?
gives up the processor and allows it to process other threads.
Thread#yield() is the java counterpart to relinquish the control of the processors voluntarily.
From the javadoc for java.lang.Thread#yield():
A hint to the scheduler that the current thread is willing to yield its current use of a processor. The scheduler is free to ignore this hint.
Yield is a heuristic attempt to improve relative progression between threads that would otherwise over-utilise a CPU. Its use should be combined with detailed profiling and benchmarking to ensure that it actually has the desired effect.
It is rarely appropriate to use this method. It may be useful for debugging or testing purposes, where it may help to reproduce bugs due to race conditions. It may also be useful when designing concurrency control constructs such as the ones in the java.util.concurrent.locks package.
Note:
In case of Java based desktop UI frameworks like Swing, RIM's UI application, there are ways to modify the UI using invokeLater() type of semantics.
Having moved from VB6 to Java myself and having searched for an answer to this very same question at the time, I can tell you that I had to change my way of thinking about how to do things. The need for "doEvents" is most likely due to you attempting to write a Java program in the same way you wrote VB6 or an attempt to port a VB6 project "line by line" to Java. Neither is a good idea. Take a good look at the swing tutorial (if this is about UI) and the threading tutorial whether it is UI or not. Pay a close attention to and try to understand how the Event Dispatch thread works. I found the Java tutorials to be a great starting place, they are now located at Oracle: http://docs.oracle.com/javase/tutorial/ look at the samples and read the code, they are a good place to learn/experiment
You need to start thinking in Java and not translate VB6 to Java, it took me a while to get there but not too long and overcoming the need for "doEvents" will take you a long way down that path if you understand the way around it. Good luck, and welcome to Stackoverflow, this is a great place to look for help!

How can OpenMP be used inside Java code?

I have a Java project, in which I have to achieve parallelization through OpenMP technology (that is, I have to, somehow, make a bridge between C/C++ and Java). So far I was told about using JNI for integrating C/C++ code in java, but, also I was suggested to use JaMP instead. I don't know much about these techniques/frameworks, so my question is, which is less pain to use, and, generally, how can I implement OpenMP stuff in Java code? Can I achieve the same functionality using only Java threads (without using OpenMP)? I'm a beginner in this domain, so absolutely any help is much appreciated.
Hint: the project is to build a collaborative graphic editor, by "putting" onto one core the interactions between the server and the clients, and "putting" onto another core the effective graphic processing.
From your brief and slightly confusing explanation of your project I don't see any need for you to be using OpenMP at all. All that you want to do can be done entirely within Java which has good (enough) facilities for concurrent programming.
OpenMP was designed for a completely different type of 'concurrent' program -- really for parallel programs; at its heart it's for spreading loop iterations across processors. This is not a good fit to your problem.
If you have been told that you must use Java and OpenMP then I suppose you must. If this is so, go with JaMP. Only if someone holds a gun to your head should you set out on the path of Java+JNI+C/C+++OpenMp.
Futures can also be given a look for your project.
Which I think is not used by many traditional programmers for parallelizing their work.

Java Swing - UI Freezing

I'm doing some routine in Java (1.5)+Swing, that damands some time. How the best way to implement this routing outside the swing thread, to avoid UI freezing?
Thanks in advance
At first blush, look at the SwingWorker class. When you want to make the code more robust and testable, you probably want to move away from that, but it is a good enough first start.
You can get a version for Java 1.5 here. With 1.6 it is part of the standard API.
Using SwingWorker is of course good idea and I recommend that. Also writing custom javax.swing.Timers and java.lang.Threads .
But don't forget to use profiler - it can help you to find many problems. Like Swing is often having trouble with "dead" Listeners holding some references which can not be garbage collected (resulting in very slow responses or freezing of UI or even memory leaks). Profiler will help you to investigate memory needs of specific situations when using your application and therefore you might be able to do fine tuning of your app.
Resolved as comment:
"This could help: stackoverflow.com/questions/2564388/javas-swing-threading – Andreas_D Jul 5 at 22:01"

Which Java APIs create Threads

Without having the source code for a Java API, is there anyway to know if the API methods create multiple threads ? Are there any conventions to follow if you are writing Java APIs and they create multiple threads. This may be very fundamental question but it happened to spawn out of a discussion in which the crux question was - " How do you know which Java APIs create threads and which don't " ?
One way of determining which libraries create new threads is by disallowing Thread creation and ThreadGroup modification in the SecurityManager. See the java.lang.SecurityManager.checkAccess(Thread) method. By implementing your own SecurityManager, you are able to react on the creation of Threads.
To answer the other question: many libraries create new threads, even if you don't expect it. For example APIs for HTTP communication create Timers for Keep-Alives or session timeouts. Java 2D is creating a signalling thread. Java itself has multiple threads, e.g. the Finalizer thread; the AWT/Swing event dispatcher thread etc.
There's no way to tell. Actually, I don't think you normally would care that much unless you're in some kind of constrained environment. What's I've found is more relevant is to determine if a method is written with an expectation of being run on a particular thread (the AWT Event dispatch thread, in the case I've seen). There's not a way to do that either, unless the code is using some kind of naming convention, or it's documented.
In my experience, if you are looking at core java, not J2EE, the only time I can think that threads are created in core Java is with Swing.
I haven't seen any example of other threads being created by the core Java APIs, except for the Thread class, of course. :)
But, if you are using other libraries then it may be that they are creating threads, but, if you don't want to profile, you may want to use AspectJ to log whenever a new thread is created, and the stack track of what called it, so you can see what is creating the threads.
UPDATE:
Swing uses 4 threads, according to this post, but he also explains how you can go about killing off the threads, if needed.
http://www.herongyang.com/Swing/jframe_2.html
If you want to see active threads, just fire up the jvisualvm application (located in your $JDK/bin directory) to connect to any local java process. You'll be able to see a multitude of information about the process, including thread names, status, and history. Get more information here.

Categories