Java swing and threading issue

i am trying to update swing components from some thread. at my first try, i noticed this was a disaster. upon further research, i found out about the single-threaded model of swing events (i.e. event dispatching thread).
i did more research and could NOT find a good example on how to update swing components from other threads. many examples were showing too much.
can someone post a simple example on here? i just want to see how to properly update a swing component from a non-swing class using threading.

I think its a simple example:
http://forum.java.sun.com/thread.jspa?forumID=57&threadID=621226
Let us know what you think.

Similar Messages

  • JDK 1.6 on Solaris. Multiple java processes and thread freezes

    Hi, we've come across a really weird behavior on the Solaris JVM, reported by a customer of ours.
    Our server application consists of multiple threads. Normally we see them all running within a single Java process, and all is fine.
    At some point in time, and only on Solaris 10, it seems that the main Java process starts a second Java process. This is not our code trying to execute some other application/command. It's the JVM itself forking a new copy of itself. I assumed this was because of some JVM behaviour on Solaris that uses multiple processes if the number of threads is > 128. However at the time of spawn there are less than 90 threads running.
    In any case, once this second process starts, some of the threads of the application (incidentally, they're the first threads created by the application at startup, in the first threadgroup) stop working. Our application dumps a list of all threads in the system every ten minutes, and even when they're not working, the threads are still there. Our logs also show that when the second process starts, these threads were not in the running state. They had just completed their operations and were sleeping in their thread pool, in a wait() call. Once the second process starts, jobs for these threads just queue up, and the wait() does not return, even after another thread has done a notify() to inform them of the new jobs.
    Even more interesting, when the customer manually kills -9 the second process, without doing anything in our application, all threads that were 'frozen' start working again, immediately. This (and the fact that this never happens on other OSes) makes us think that this is some sort of problem (or misconfiguration) specific to the Solaris JVM, and not our application.
    The customer initially reported this with JDK 1.5.0_12 , we told them to upgrade to the latest JDK 1.6 update 6, but the problem remains. There are no special JVM switches (apart from -Xms32m -Xmx256m) used. We're really at a dead end here in diagnosing this problem, as it clearly seems to be outside our app. Any suggestion?

    Actually, we've discovered that that's not really what was going on. I still believe there's a bug in the JVM, but the fork was happening because our Java code tries to exec a command line tool once a minute. After hours of this, we get a rogue child process with this stack (which is where we are forking this command line tool once a minute):
    JVM version is 1.5.0_08-b03
    Thread t@38: (state = IN_NATIVE)
    - java.lang.UNIXProcess.forkAndExec(byte[], byte[], int, byte[], int, byte[], boolean, java.io.FileDescriptor, java.io.FileDescriptor, java.io.FileDescriptor) @bci=168980456 (Interpreted frame)
    - java.lang.UNIXProcess.forkAndExec(byte[], byte[], int, byte[], int, byte[], boolean, java.io.FileDescriptor, java.io.FileDescriptor, java.io.FileDescriptor) @bci=0 (Interpreted frame)
    - java.lang.UNIXProcess.<init>(byte[], byte[], int, byte[], int, byte[], boolean) @bci=62, line=53 (Interpreted frame)
    - java.lang.ProcessImpl.start(java.lang.String[], java.util.Map, java.lang.String, boolean) @bci=182, line=65 (Interpreted frame)
    - java.lang.ProcessBuilder.start() @bci=112, line=451 (Interpreted frame)
    - java.lang.Runtime.exec(java.lang.String[], java.lang.String[], java.io.File) @bci=16, line=591 (Interpreted frame)
    - java.lang.Runtime.exec(java.lang.String, java.lang.String[], java.io.File) @bci=69, line=429 (Interpreted frame)
    - java.lang.Runtime.exec(java.lang.String) @bci=4, line=326 (Interpreted frame)
    - java.lang.Thread.run() @bci=11, line=595 (Interpreted frame)There are also several dozen other threads all with the same stack:
    Thread t@32: (state = BLOCKED)
    Error occurred during stack walking:
    sun.jvm.hotspot.debugger.DebuggerException: can't map thread id to thread handle!
         at sun.jvm.hotspot.debugger.proc.ProcDebuggerLocal.getThreadIntegerRegisterSet0(Native Method)
         at sun.jvm.hotspot.debugger.proc.ProcDebuggerLocal.getThreadIntegerRegisterSet(ProcDebuggerLocal.java:364)
         at sun.jvm.hotspot.debugger.proc.sparc.ProcSPARCThread.getContext(ProcSPARCThread.java:35)
         at sun.jvm.hotspot.runtime.solaris_sparc.SolarisSPARCJavaThreadPDAccess.getCurrentFrameGuess(SolarisSPARCJavaThreadPDAccess.java:108)
         at sun.jvm.hotspot.runtime.JavaThread.getCurrentFrameGuess(JavaThread.java:252)
         at sun.jvm.hotspot.runtime.JavaThread.getLastJavaVFrameDbg(JavaThread.java:211)
         at sun.jvm.hotspot.tools.StackTrace.run(StackTrace.java:50)
         at sun.jvm.hotspot.tools.JStack.run(JStack.java:41)
         at sun.jvm.hotspot.tools.Tool.start(Tool.java:204)
         at sun.jvm.hotspot.tools.JStack.main(JStack.java:58)I'm pretty sure this is because the fork part of the UnixProcess.forkAndExec is using the Solaris fork1 system call, and thus all the Java context thinks all those threads exist, whereas the actual threads don't exist in that process.
    It seems to me that something is broken in UnixProcess.forkAndExec in native code; it did the fork, but not the exec, and this exec thread just sits there forever. And of course, it's still holding all the file descriptors of the original process, which means that if we decide to restart our process, we can't reopen our sockets for listening or whatever else we want to do.
    There is another possibility, which I can't completely rule out: this child process just happened to be the one that was fork'd when the parent process called Runtime.halt(), which is how the Java process exits. We decided to exit halfway through a Runtime.exec(), and got this child process stuck. But I don't think that's what happens... from what I understand that we collected, we see this same child process created at some point in time, and it doesn't go away.
    Yes, I realize that my JVM is very old, but I cannot find any bug fixes in the release notes that claim to fix something like this. And since this only happens once every day or two, I'm reluctant to just throw a new JVM at this--although I'm sure I will shortly.
    Has anyone else seen anything like this?

  • Swings and Threads

    My applet communicates with the database. To ensure that the GUI is updated in the Event-Dispatching Thread I am using a SwingWorker: in construct() the application communicates with DB, and in finished() it updates the GUI. In construct() of the SwingWorker thread I need to create a dialog box to prompt the user for an input like to chose a color or to answer yes/no.
    My question is: Do I need to use invokeAndWait() to create the dialog box? The more general question is: do we use invokeLater() or SwingWorker only for GUIs that are shared by several threads or we have to use it for every swing we create after Event-Dispatching Thread started running?
    Thank you

    One of the fun things about Swing and its EventDispatchThread is that
    doing things wrong (such as performing Swing operations from a thread
    other than the EDT) is that more often than not, even though they are done
    technically wrong, they will still appear to work, especially in small programs.
    (In a larger sense, this applies to any multi-threaded program: things might
    appear to work until the timing changes just a teensy bit...)
    What's even more fun is working with someone who has previously only
    done small programs and because of that, takes this approach in large programs, and then spending a large amount of time trying to figure out why
    something sporadically stops working, only to trace it back to a Swing
    operation being invoked from a thread other than the EDT. Fun!
    You know how to do it correctly.
    You know why to do it correctly.
    But you choose not to. Good luck with that.

  • Parallel function call and thread issue

    Sorry to post one issue here which is related to code. i was debugging a code which was wrote long time back by one developer. the issue is two function is called parallel using thread and one function set a variable true at end and another function just
    looping until the variable is set to true. the variable value is not getting set to true. here i am posting a code snippet and just tell me what is mistake in the code for which variable is not getting set to true by first function.
    when user click button then two function is invoked
    private void UPDATE_Click(object sender, System.EventArgs e)
    SavedFirst();
    AddCheckThread();
    public void SavedFirst()
    IsOpen = true;
    System.Threading.Thread loadT = new System.Threading.Thread(new System.Threading.ThreadStart(SaveAll));
    loadT.Start();
    IsOpen = false;
    private void AddCheckThread()
    if (!ALLFlag)
    loadingThread = new System.Threading.Thread(new System.Threading.ThreadStart(addCheck));
    loadingThread.Priority = System.Threading.ThreadPriority.Lowest;
    loadingThread.Start();
    private void SaveAll()
    if (this.InvokeRequired)
    this.Invoke(new MethodInvoker(delegate
    ALLFlag = false;
    if (!ALLFlag)
    loadingThread = new System.Threading.Thread(new System.Threading.ThreadStart(AddProducts));
    loadingThread.Priority = System.Threading.ThreadPriority.Lowest;
    loadingThread.Start();
    return;
    private void AddProducts()
    if (this.InvokeRequired)
    this.Invoke(new MethodInvoker(delegate
    ALLFlag = false;
    if (System.Windows.Forms.MessageBox.Show(this, "Would you like to add the details into the Database?", "Add?", System.Windows.Forms.MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
    if (comboOUR.SelectedItem == null || comboCountry.SelectedItem == null || comboSelleble.SelectedItem == null || txtOereff.Text == "" || txtUKPrice.Text == "" || txtUSPrice.Text == "" || txtSUrCharge.Text == "" || txtOURUS.Text == "" || txtOURUK.Text == "")
    FormValidation();
    else
    Gather_Data();
    bool isInserted = false;
    if (System.Windows.Forms.MessageBox.Show(this, "Would you like to add the details into \"Detailed-Product\" Too?", "Add?", System.Windows.Forms.MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
    isInserted = bbaProduct.BBASaveProduct();
    if (isInserted == true)
    isInserted = false;
    isInserted = bbaProduct.InsertInProductTable(BBAProduct.DetailProductID);
    if (isInserted == true)
    System.Windows.Forms.MessageBox.Show(this, "Product Successfully Added ", "Add");
    else
    System.Windows.Forms.MessageBox.Show(this, "Error Occurred !! Not Added Into the Database ", "Add");
    else
    System.Windows.Forms.MessageBox.Show(this, "Error Occurred !! Not Added Into the Database ", "Add");
    else
    isInserted = bbaProduct.InsertInProductTable(0);
    if (isInserted == true)
    System.Windows.Forms.MessageBox.Show(this, "Successfully Inserted Into the database", "Add");
    else
    System.Windows.Forms.MessageBox.Show(this, "Error Occurred !! Not Added Into the Database", "Add");
    else
    System.Windows.Forms.MessageBox.Show(this, "Process Cancelled By The User", "Add");
    ALLFlag = true;
    return;
    #region Add Check
    private void addCheck()
    if (this.InvokeRequired)
    this.Invoke(new MethodInvoker(delegate
    this.Opacity = 0.8;
    axShockwaveFlash1.Visible = true;
    axShockwaveFlash1.Play();
    while (!ALLFlag)
    int x = 0;
    axShockwaveFlash1.Visible = false;
    axShockwaveFlash1.Visible = false;
    axShockwaveFlash1.StopPlay();
    this.Opacity = 1;
    ALLFlag = false;
    loadingThread.Abort();
    return;
    help me to locate where is the mistake for which ALLFlag value is not getting set to true. thanks

    Your reliance on a field value across threads isn't going to work reliably.  In a multi-core/multi-threaded world the memory model allows for reading data out of order for optimization reasons.  Additionally the CPU can and will cache recently
    used data in memory that isn't shared across processors.  This can get you into trouble as you will not be reading the same value across processors.
    The only correct way to ensure that multiple threads access the same data correctly is to use sync objects that are designed for that such as a Semaphore or Mutex.  Sync objects allow you to safely share data across threads.
    Overall your code appears to be trying to update the UI using a thread but since it is calling Invoke each time you are basically spawning a thread that then blocks waiting for the UI thread.  You could pretty much eliminate your issues by getting rid
    of the threading calls altogether along with any sort of state management variables that were arbitrarily created (ALLflags) and simply use BeginInvoke.  You didn't post who was calling your higher level save methods but if it is a UI element then BeginInvoke
    and InvokeRequired are completely redundant as is all the threading.
    You can cleanly update this code to eliminate all the extra variables and threading and simply use the newer async/await functionality to help resolve the issues your code is having.  But you still have problems with the invoked code.  In one of
    the methods you are looping while waiting for a variable to be set.  But since you invoked it then it is occurring on the UI thread.  Because it is on the UI thread and that can only do 1 thing at a time, if ALLflag is false your code will deadlock. 
    The only other code that would set it to true cannot run because it is also invoked on the UI thread and only one of them can run at any one time.  Basically each of your threads are going to try to run on the same thread and only 1 of them will be able
    to.  Until the first thread method finishes the second one will never run.
    If you need Boolean flags then consider using a ManualResetEvent instead.  It is thread safe, works across threads and doesn't have any of the problems of a Boolean field when talking about threading. But you still have a deadlock between your invoked
    code that nothing will solve except rewriting your code.
    Michael Taylor
    http://blogs.msmvps.com/p3net

  • Java Swing and Flash

    Is it possible to create flash components (swf files) and include them in a Swing JFrame and be able to post data from and to it.
    For example, if the swf gui is showing a list of items, the list is coming from the Java application and then the SWF file gets included in a Swing JFrame. When user chooses an item from the list and clicks a button then the results is passed back to the Java application.
    Has anyone done something similar to this? How is this possible? Code samples would be appreciated.

    May be you can try out JFlash ...
    https://jflash.dev.java.net/
    They support only upto Flash 2 player... and it is still under development i guess...

  • Java Swing and Socket Programming

    I am making a Messenger like yahoo Messenger using Swing and Socket Programming ,Multithreading .
    Is this techology feasible or i should try something else.
    I want to display my messenger icon on task bar as it comes when i install and run Yahoo Messenger.
    Which class i should use.

    I don't really have an answer to what you are asking. But I am developing the same kind of application. I am using RMI for client-server and server-server (i have distributed servers) communication and TCP/IP for client-client. So may be we might be able to help each other out. My email id is [email protected]
    Are you opening a new socket for every conversation? I was wondering how to multithread a socket to reuse it for different connections, if it is possible at all.
    --Poonam.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Java 2D and 3D issue

    Hello everyone,
    I'm new to Java graphics and have been trying to figure out the best way to improve my particular application. It is dynamic and refreshes at about 75Hz. It contains lots of data points and seems to flicker a lot.
    I've concluded that rendering the data may be the problem as I am currently using BufferedImage types, which renders in software if I'm not mistaken.
    Now, I've been researching on ways to improve performance by delegating the rendering on VRAM and take advantage of hardware acceleration. What I've discovered is that a new image type has been introduced in Java 1.4 I believe, and this is called VolatileImage, check this link out: java.sun.com/products/java-media/2D/perf_graphics.html and scroll to the section "Hardware Acceleration for Offscreen Images", it has a brief explanation. It apparently takes advantage of hardware acceleration.
    I have also discovered that hardware acceleration can also be achieved using OpenGL Java bindings or something along those lines and you can have a look here: http://www.opengl.org/resources/java/. Of course OpenGL mainly deals with 3D graphics so hence I'm confused as to what direction I should take.
    Either use VolatileImage or OpenGL. VolatileImage is for 2D graphics and the OpenGL is for 3D graphics. I'm confused because OpenGL can also be used for 2D and I'm not sure which one I should use for my application. I'd like to use the most efficient solution possible. Any ideas. Your feedback would be much appreciated.
    Cheers,
    Mitch.

    Personally (for me...) I think it be bether you'd say in more detail what you wanna achieve. (What do you "put on screen"?)
    For me, just using BuferedImage(s) for my picture image editor works fine for me (when I switched from "new BufferedImage(...)" for every frame (flickered much more for me too) to reuse BufferedImage(s)). Of course, for that (use) I don't have a refresh rate of 75 Hz, and I don't really "render" (only ... draw...Image(...), ...).
    But J3D I only use for my 3D "virtual universe". (Might you wanna check out "OpenGL" on Wikipedia?)
    I must confess, I don't know that much about "2D(!) rendering" (can one really say that?) myself.

  • Java Swing and windows listview control

    Hi,
    many programming languages have the listview control, to which you can define diferents kinds of data's organizers as Icon, Detail, List, etc.
    Somebody knows if java swing have a component as the listview ?
    thanks

    Yes. It's called JList. Have a look at the tutorial:
    http://java.sun.com/docs/books/tutorial/uiswing/index.html

  • Logging Java objects and threads. Application sampling.

    I am using a laptop to run my application on. It uses windows XP and it is the only application running on that machine. I use TCP and serial port to communicate to other devices. My application is supposed to use up to 300M of memory but apparently it using much more than that. The laptop physical memory size is 512M. I am wondering if there is a way to sample my application periodically. What I mean by that is, after the applications runs I want to run at the same time kind of profiler that every, let us say, 10 minutes logs the number of objects created and what those objects are or what the current ones are. The number of threads running and what are their names. I want to know what is using all of this memory. The memory usage goes up to about 420M. As a result, the application throws out of memory exception. I believe I can get the number of threads running but do not know how to get their names. I need to know all of that so I would go into my code and see where it is happening and try to solve the problem. One of the ways I have in my mind now is to put a print out everywhere I create an object or thread, but that�s very expensive. Any hints or tips could be useful.
    Thank you in advance.
    P.S.:
    I do not want to run a profiler such as JProfiler because the application is running live and I do not have access to it. I want to embed these logs into the application itself and rerun it on a live system.

    As a first thought, I'm guessing that you're merely thinking that your program will not exceed 300 megabytes just based on the -Xmx300M command you may be passing your program. This is a max heap size, not the max footprint your program will take. Be aware that this can go beyond the scope of 300 MB....
    Now, if you want very detailed information about processes, memory usage, etc, you might be able to keep track of it yourself, but if you want this information from a system-level sort of thing you will not get it, as one of the major points of Java is that it does not care about a lot of system specifics.
    Now, if you're really interested in keeping track of threads, I don't see why you could not just write to a log file every time you spawn a new thread of a particular kind.

  • Java Swing and WIndows User Localles

    HI,
    We need to develop a java applet/application which can be switchable at run time to accept and display characters in multilanaguages. This java applet will run on a windows 2000 server with multilanguage pack installed. Is it possible to dynamically switch languages at run time. The machines default localle and operating system installation is US English.
    We have tried some tests with traditional chinese and UI components in Swing but with no success in displaying or inputing valid chinese characters. Has anyone attempted a simliar thing and have any insights that may help.
    Thanks in Advance,
    Jono

    Yes. It's called JList. Have a look at the tutorial:
    http://java.sun.com/docs/books/tutorial/uiswing/index.html

  • [Solved] Java applications and awesome issue

    Hello Folks,
    I know this issue has been solved before, but it didn't work for me:
    You all know the issue with the grey windows when starting a java application, right? Well, I have that issue too and I'd like to bring that to work.
    I read this article   http://awesome.naquadah.org/wiki/Problems_with_Java   but the workarrounds didn't work (I didn't try the second one with wmname).
    Is there yet any other know workarround? I also tried this one but that one didn't work eighter:
    export AWT_TOOLKIT=MToolkit
    [tectu@mercur ~]$ awesome -version
    awesome v3.4.11 (Pickapart)
    • Build: Apr 27 2012 09:01:08 for x86_64 by gcc version 4.7.0 (nobody@archbuild)
    • D-Bus support: ✔
    [tectu@mercur ~]$ java -version
    java version "1.7.0_03-icedtea"
    OpenJDK Runtime Environment (IcedTea7 2.1) (ArchLinux build 7.b147_2.1-3-x86_64)
    OpenJDK 64-Bit Server VM (build 22.0-b10, mixed mode)
    [tectu@mercur ~]$
    Does somebody have a working solution for me?
    ~ Tectu
    Last edited by Tectu (2012-05-24 11:21:17)

    Oh, the 'wmname LG3D' solution did work indeed.
    I was just curious about saying that I use a different window manager, that I thought I'm just gonna try the two other solutions.
    Thank you guys!

  • Re: Java Images and Threads prob Help!!

    Without going through it in detail the problem may be that you're doing the repaint which you hope will draw the image before the image has completed loading.
    Create your ImageIcon (loading the "xxxx.jpeg" files) during program initialisation. And check the load status of the icon, at least in a test version.

    I still cant get the reqd output. Only the 1st image is dispayed and when i click the second code, the 2nd image doesnt come(the first one does not disappear, and even when i click the code 1 i have to minimize/ maximize the screen, to get the image and after that it does not go for the s2nd image 2 come!! )
    Create your ImageIcon (loading the "xxxx.jpeg" files) during program >>initialisation. And check the load status of the icon, at least in a test version. How do u load the image during initialization??? and can ny1 plz tell me how to get the flashing threads with msgs????

  • Java deadlock and performance issue

    Hi Team,
    there is one problem in my application, facing performance problems.
    Here is the situation, please advice if you have some idea with below
    situation.
    Problem :
    There are two events with me and sharing the data from single table.
    Now both the events are running sequentially in a single thread. So
    that it is taking lot of time to process these two events
    sequentially.
    My approach : Now I want to try the above two events with
    multi-threaded event process in parallel. But fearing about the
    deadlock situation which will occur at the time of update data of the
    table.
    Need your help : Please let me know if there is any solution to
    avoid deadlock by using multi thread(as above situation) or any other
    alternate solution to the same.
    your help will be appreciated.

    Nethi_Ravi wrote:
    I can use synchronize but both the threads are updating single table to update the data. There may be chances of deadlock. My application scenario is some what similar to this situation, to understand more clear I have given the above exmple.
    Moreover syncronize keyword is the main problem for deadlock.
    -RaviI think you are confused about what a deadlock is. Deadlock is not same as lock. When a thread updates a table, it acquires a lock more precisely a row lock on the row its updating. When you write a synchronized static method, you are telling threads to acquire a class lock (different from table lock) which is bound to block one of the threads.
    If the synchronized method calls another synchronized method, you can run into a deadlock. When 2 threads wait on each other to release a lock, thats a deadlock situation. So make sure the synchronized method doesn't call another synchronized method and you will NEVER run into a deadlock!

  • Java Swing and Microsoft Excel

    How do you open a Microsoft Excel  file from swing?
    please give a example.

    Hi,
    try these APIs:
    [http://poi.apache.org/]
    [http://jexcelapi.sourceforge.net/]
    Once you get the content of the files, it's up to you how you display it in your swing application.
    Demos and tutorials can be found on these sites as well.

  • Send image with MFMailComposeVewController and thread issue

    Hi,
    In my app, if user click a button, the app will generate an image and show up a MFMailComposeViewController with the image as attachment. Since it takes quite some time to generate the image, I fired up a thread and generate the image in this new thread. I am not sure what to do the next. When the image is generated, how can I tell the mail thread to launch the MFMailComposeViewController?
    Thanks,
    ff

    Have you looked at this sample yet (link)?

Maybe you are looking for

  • Warning Using in Water 4 Day Old Z3 Tablet Leaked

    Just wanted to give a warning to all Z3 tablet owners, my experiance may just be an unlucky one off or could be a flaw in the design of the device. Had my Z3 tablet for 4 days and tonight I used it to browse in the bath. Something I have done 100's o

  • Logging in to WiFi server

    For some reason our iPod (4th G) will only let us use capital letters on the first letter of the WiFi passcode. Since the whole thing is case sensitive, we cannot log into our own wifi server. Any suggestions?

  • Sharing Internet Connection from iMac to MacBook Pro

    I've arrived home for the holiday from university and, of course, brought my MacBook Pro home with me. My family does not have a wireless Internet connection as I do at uni, but they do have an iMac connected to a cable modem via ethernet. So I have

  • Pantone different from other apps.

    Hello people, I'm designing a 1-colour flyer using Pantone 2602. The file contains a mono-tone image created in Photoshop and an eps logo generated in Corel Draw, both using 2602. Paper-coloured text is placed over a rectangle filled with 2602. Howev

  • Processes in account stops or not?

    Hey all, just a quick question. Let's say I'm logged in to one account and doing some stuff there, like backing up or repairing the permissions. If I log into another account, will all those processes continue? Sounds simple, but I need to know. TIA!