InvokeLater() and invokeAndWait()

I'm somewhat confused about when to use these.
from http://java.sun.com/docs/books/tutorial/uiswing/misc/threads.html - it says "you must take extreme care that Swing components and models are created, modified, and queried only from the event-dispatching thread"
I also understand that these two methods are basically the same though invokeAndWait only returns once the run() has completed while invokeLater will return immediately.
So, when should I use these? and which one should I use?
If I'm creating the GUI initially, use the invokeAndWait()
If I'm updating/quering the GUI components, use invokeLater()
is this the correct way of thinking?

You only need to use these methods if you are updating your GUI from a Thread you have spawned. These methods insure the GUI udpate is performed from the event dispatcher thread as those methods put the GUI update in the event queue.
If you are already updating the GUI from the event dispatcher thread (i.e. from an ActionListener, MouseListener, etc) you don't need to use them.
For instance lets say you do an expensive database query (takes a noticeable amount of time to return results) when you press a button. If you just do the database query in the main thread the rest of your application will block while the db query is performed. So you would spawn a new thread with your db query in it. However, now lets say when the db query is over you want to update some status label to notify the user. You would put the label update in a Runnable object and pass that to invokeLater() which would put your runnable oject in the event queue which would eventually get executed by the event dispatcher thread.
Now the rest of your application is responsive while the db query is occuring. And the label will be updated in a thread safe way when the db query is done.
Generally invokeLater() is used, as invokeAndWait() blocks until the runnable object you add to the event queue is executed. This isn't generally desireable. More or less you can safely ignore invokeAndWait(), although keep it in mind for those rare occasions where its usage would be desireable.
Here a very generic example:
public void actionPerformed(ActionEvent e) {
      //Button has been pressed lets query the db in a thread
      new Thread() {
            public void run() {
                //Hit the DB
                Runnable changeLabel = new Runnable() {
                    public void run() {
                        label.setText("tell user db query is done");
                //Put the changing of the label in the event queue
                EventQueue.invokeLater(changeLabel);
        }.start();
}

Similar Messages

  • Help on invokelater and invokeandwait

    Hello,
    i am developing an application using swing API.
    in this application i have to read ceratin data from the database. and do operation on the data.
    what i want to do is to fetch data based on a query and display the data to the user in a JTable on a separate JFrame. the user selects the row from the table, he wants to process and presses the select button on this frame, to set the static variable (say ROW_ID) in the class whcih invoked this frame.
    now what should happen is that the invoking class object should wait untill i press the select button (ie when the ROW_ID is set).
    i would like to know how to do it.
    please help
    thank you
    Message was edited by:
    vaibhavpingle

    now what should happen is that the invoking class object should wait untill i press the select button (ie when the ROW_ID is set).
    It doesn't sound like you want invokeLater() or invokeAndWait().
    I think you want one of two things: the more likely is that you want to be using a modal JDialog to allow the user to select a row (if you display the table, make the selection and then close that new window). The other possibility is that you want your original object to have state, which is modified (on the Event Dispatch Thread) when the user makes the row selection. Until that state is modified, certain functionality is disabled.
    i also tried to use the invokeAndWait(runnable) method but i got an exception saying that the call cannot be made
    What exception? I don't know of one which says "the call cannot be made."

  • InvokeLater() and invokeAndWait(): concerns over synchronization

    I've been reading up on the methods invokeLater(Runnable) and invokeAndWait(Runnable) and I've understood this much: the difference is in the synchronization of the new thread with the main (or current) one. I somewhat familiar with what synchronization means (i.e. it's a way of guaranteeing that changes made to shared resources are seen by all threads as soon as they are made).
    My question is: does a call to invokeAndWait() mean that I don't have to worry about synchronizing methods and code?

    gib65 wrote:
    My question is: does a call to invokeAndWait() mean that I don't have to worry about synchronizing methods and code?No. Both the invoke methods just push off code to be executed in the event thread. That might mean that you don't need synchronization, but only if the synchronization was needed because you had the event thread and another thread accessing same resources.
    The difference is that invokeLater doesn't stop the execution of the current thread, while invokeAndWait stops the current thread until the task has been run on the event thread.

  • Question on SwingUtilities.invokeLater

    The program I have included is attempting to "simulate" opening and loading a file into memory.
    Run the program, select File and then select Open. You will notice that the File menu does not disappear for 3 seconds (i.e. until the file has been completely read).
    I was hoping it was possible to close the File menu while the file is being read. While reading through various documentation on the invokeLater() method I found the following:
    "Both invokeLater() and invokeAndWait() wait until all pending AWT events finish before they execute"
    Therefore by adding an invokeLater() method I was hoping to accomplish the following series of events:
    1) click on Open menuItem
    2) invoke OpenAction
    3) do the "repaint" (which would cause the file menu to disappear)
    4) finish the OpenAction
    5) do the long running task
    Hopefully you understand what I am trying to accomplish and can provide some guidance. Here is the sample program:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class TestInvokeLater extends JFrame
         JFrame frame;
         JMenuBar menuBar;
         JMenu menu;
         JMenuItem menuItem;
         public TestInvokeLater()
              frame = this;
              setDefaultCloseOperation( EXIT_ON_CLOSE );
              menuBar = new JMenuBar();
              menu = new JMenu("File");
              menuBar.add(menu);
              menuItem = new JMenuItem( new OpenAction() );
              menu.add(menuItem);
              setJMenuBar( menuBar );
              JPanel panel = new JPanel();
              panel.setPreferredSize( new Dimension( 100, 100 ) );
              setContentPane( panel );
         class OpenAction extends AbstractAction
              public OpenAction()
                   putValue( Action.NAME, "Open" );
              public void actionPerformed(ActionEvent e)
              repaint();
         SwingUtilities.invokeLater(new Runnable()
         public void run()
              try
                   Thread.sleep(3000); // simulate log running task
              catch (Exception e) {}
         public static void main(String[] args)
              JFrame frame = new TestInvokeLater();
              frame.pack();
              frame.show();
    }

    Thanks for the input, but I still have some confusion -
    "invokeLater() simply appends the thread to the end of the dispatch queue, this happens before the event code to hide the file menu gets queued"
    This is the part that confuses me. If I understand event driven programming correctly then the code for the MenuItemClicked must complete execution before the next event in the queue can be executed.
    If we assume the code for MenuItemClicked is something like:
    1) fireActionEvent
    2) fireCloseMenuEvent
    When MenuItemClicked is finished executing the next event in the queue is the ActionEvent which invokes my ActionPerformed code:
    1) I use the Swing invokeLater() method (which means it should be queued "after" the fireCloseMenuEvent
    Does this make any sense?

  • More Mac OS X Fullscreen Issues

    Howdy all,
    Having an interesting problem on Mac OSX 10.3.4. Seems that if you try to start full screen exclusive mode from the AWT-Event thread, it hangs forever.
    I have a swing app for displaying a slideshow, and want it to display fullscreen. The app functions perfectly on Windows and Linux, but hangs forever on Mac OS.
    It was particularly annoying because all the test programs from Sun ran fine, but my app would hang. I spent a some time tracking it down, and it seems that full screen exclusive mode can be started from any thread EXCEPT the AWT-Event thread. This is troubling because I just want to make a swing app use fullscreen mode, and if I can't use the AWT-Event thread I will need to write my own renderer.
    Anyone had this issue? Known bug? Any common work-arounds?
    Thanks,
    -g

    I've been having a look around the FullScreen APIs recently and have have equal measure of success and failure on both MacOsX and Windows. (I read somewhere that possibly MacOsX3.5 sorts out some teething troubles so i'll be trying that tonight).
    I also saw that on the Mac you need to use a different thread, but in doing so I am suspicious that a whole bunch of race condition issues are being thrown up when you try changing display mode etc . the online book at fivedots about java gaming suggests that you need to call some fullscreen methods in the event dispatch thread, so as you can imagine i'm getting bogged down.
    I think there needs to be some good literature on the net from Sun about the intended threading models for fullscreen and windowing mode. The tutorial says one should avoid mixing the two models, but this is not good enough - i want to be able to switch between windowing and active rendering easily, and also to be able to shut down the EDT as well and drop from a gui-based work mode to console with the same app.
    I've been going round in circles trying to find and trying to write code that works a) on one platform and b) on both platforms where windowing and fullscreen switching is involved. I have tried setting up non-EDT threads that immediately call back into the EDT to adjust properties of the fullscreen window etc to try to avoid locking up the EDT. I'm perfectly happy with the invokeLater and invokeAndWait calls, but fullscreen implementations on windows and MacOsX are really hard
    Can anybody shed some light? What's going on? Whats the intended threading model here?
    Thanks in advance

  • How to add new component to JFrame dynamically?

    Hello,I'm now study the GUI and here i meet a problem.I want to display a pic use JComponent.In paint() method i paint the pic.because i use a button to open a FileDialog to choose a pic file and send the path info to the constructor of JPicPane(i extends it from JComponent),so it will be add to the frame when it was visible and we know that there is a swing thread problem.so i use invokeLater(new Runnable(){....pack();});I want to know besides pack() can i use other method to change the layout sothat the new component could be displayed.becasue pack() will make the frame changeits size.(it displays the preferred size of components?) I don't want it make the frame change size and the component be displayed,is there any approch else?one method occur to me is chang the prefer size of contentPane sothat the pack won't make the frame small.is there any other method?and by the way,what's the different between invokeLater and invokeAndWait?
    thank you all! thank you!

    No idea why it is slow(er). The difference between invokeLater and InvokeAndWait are described here and in the tutorial that is linked there.

  • Progress bar on Applet using swing

    Not sure if this is Swing related or applet related, so I'll post it here... :-)
    Long work should be done on a Worker thread an not inside the Swing Dispacher thread .
    So normally I create a Runnable object that calls something like doWork(), and pass the runnable object as a parameter to the Sing utilities invokelater() function.
    My question is inside the worker thread how to update the GUI, in this case the progress bar?
    Can I just call from inside doWork() with no problems the progressbar.setValue(X)?
    Do I need to create another thread and use it too update the UI?
    Is something like this valid ?
    public void doWork() {
    // work work work
    progressbar.setValue(5);
    //more work
    progressbar.setValue(15);
    // and so on
    Thanks for the help!

    Not sure if this is Swing related or applet related,
    so I'll post it here... :-)It's definitely Swing related.
    Long work should be done on a Worker thread an not
    inside the Swing Dispacher thread . This is true.
    So normally I create a Runnable object that calls
    something like doWork(), and pass the runnable object
    as a parameter to the Sing utilities invokelater()
    function.This does not start a worker thread but rather schedules your Runnable object to be run on the EDT.
    My question is inside the worker thread how to update
    the GUI, in this case the progress bar?SwingUtilities or EventQueue have invokeLater and invokeAndWait specifically for this purpose.
    Can I just call from inside doWork() with no problems
    the progressbar.setValue(X)?
    Do I need to create another thread and use it too
    update the UI?No. Here's where you could use invokeLater.
    Is something like this valid ?
    public void doWork() {
    // work work work
    rogressbar.setValue(5);
    //more work
    progressbar.setValue(15);
    // and so onNo.
    >
    Thanks for the help!Like pete has pointed out, this seems to be a job for SwingWorker.

  • JTable Refreshing problem for continuous data from socket

    Hi there,
    I am facing table refreshing problem. My table is filled with the data received from socket . The socket is receiving live data continuously. When ever data received by client socket, it notify table model to parse and refresh the data on specific row. The logic is working fine and data is refresh some time twice or some thrice, but then it seem like java table GUI is not refreshing. The data on client socket is continuously receiving but there is no refresh on table. I am confident on logic just because when ever I stop sending data from server, then client GUI refreshing it self with the data it received previous and buffered it.
    I have applied all the available solutions:
    i.e.
         - Used DefaultTableModel Class.
         - Created my own custem model class extend by AbstractTableModel.
         - Used SwingUtilities invokeLater and invokeAndWait methods.
         - Yield Stream Reader thread so, that GUI get time to refresh.
    Please if any one has any idea/solution for this issue, help me out.
    Here is the code.
    Custom Data Model Class
    package clients.tcp;
    import java.util.*;
    import javax.swing.table.*;
    import javax.swing.*;
    public class CustomModel extends DefaultTableModel implements Observer {
    /** Creates a new instance of CustomModel */
    public CustomModel() {
    //super(columnNames,25);
    String[] columnNames = {"Sno.","Symbol","BVol","Buy","Sale",
    "SVol","Last","..","...","Total Vol...",
    "..","High","..","Low","Change","Average","..."};
    super.setColumnIdentifiers(columnNames);
    super.setRowCount(25);
    /*This method called by client socket when ever it recived data as line/record*/
    public synchronized void update(Observable o, Object arg){
    collectData(arg.toString());
    /*This method used to parse, collect and notify table for new data arrival*/
    public synchronized void collectData(String rec){              
    String validSymbol="";
    System.out.println("collectDataRecord :-"+rec);
    StringTokenizer recToken=new StringTokenizer(rec," ");
    Vector rowVector=new Vector();
    for(int i=0;i<25;i++){
    validSymbol=(String)getValueAt(0,1);
    if(rec.indexOf(validSymbol) != -1){
    for(int j=0;recToken.hasMoreTokens();j++){
    super.setValueAt(recToken.nextToken(),i,j);
    //break;
    Client Socket Class
    package clients.tcp;
    import java.io.*;
    import java.net.*;
    import java.util.*;
    import javax.swing.*;
    public class DataReceiver extends Observable implements Runnable{
    private Socket TCPConnection = null;
    private BufferedReader br = null;
    private String serverName = "Salahuddin";
    private int serverPort = 5555;
    public DataReceiver()
    public void setServerName(String name){
    this.serverName=name;
    public void setServerPort(int port){
    this.serverPort=port;
    //03-20-04 12:30pm Method to open TCP/IP connection
    public void openTCPConnection()
    try
    TCPConnection = new Socket(serverName, serverPort);
    br = new BufferedReader(new InputStreamReader(
    TCPConnection.getInputStream()));           
    System.out.println("Connection open now....");
    //System.out.println("value is: "+br.readLine());
    }catch (UnknownHostException e){
    System.err.println("Don't know about host: ");
    }catch (IOException e){
    System.err.println("Couldn't get I/O for "
    + "the connection to: ");
    //03-20-04 12:30pm Method to receive the records
    public String receiveData(){
    String rec = null;
    try
    rec = br.readLine();          
    catch(IOException ioe)
    System.out.println("Error is: "+ioe);
    ioe.printStackTrace(System.out);
    catch(Exception ex)
    System.out.println("Exception is: "+ex);
    ex.printStackTrace(System.out);
    return rec;     
    public void run()
    while(true)
    String str=null;
    str = receiveData();
    if(str != null)
    /*try{
    final String finalstr=str;
    Runnable updateTables = new Runnable() {
    public void run() { */
    notifyAllObservers(str);
    SwingUtilities.invokeAndWait(updateTables);
    }catch(Exception ex){
    ex.printStackTrace(System.out);
    System.out.println("Observer Notified...");*/
    try{
    Thread.sleep(200);
    }catch(Exception e){
    public synchronized void notifyAllObservers(String str){
    try{
    setChanged();
    notifyObservers(str);
    }catch(Exception e){
    e.printStackTrace(System.out);
    Regards,
    Salahuddin Munshi.

    use your code to post codes more easy to read, lyke this:
    package clients.tcp;
    import java.util.*;
    import javax.swing.table.*;
    import javax.swing.*;
    public class CustomModel extends DefaultTableModel implements Observer {
    /** Creates a new instance of CustomModel */
    public CustomModel() {
    //super(columnNames,25);
    String[] columnNames = {"Sno.","Symbol","BVol","Buy","Sale",
    "SVol","Last","..","...","Total Vol...",
    "..","High","..","Low","Change","Average","..."};
    super.setColumnIdentifiers(columnNames);
    super.setRowCount(25);
    /*This method called by client socket when ever it recived data as line/record*/
    public synchronized void update(Observable o, Object arg){
    collectData(arg.toString());
    /*This method used to parse, collect and notify table for new data arrival*/
    public synchronized void collectData(String rec){
    String validSymbol="";
    System.out.println("collectDataRecord :-"+rec);
    StringTokenizer recToken=new StringTokenizer(rec," ");
    Vector rowVector=new Vector();
    for(int i=0;i<25;i++){
    validSymbol=(String)getValueAt(0,1);
    if(rec.indexOf(validSymbol) != -1){
    for(int j=0;recToken.hasMoreTokens();j++){
    super.setValueAt(recToken.nextToken(),i,j);
    //break;
    Client Socket Class

  • How to use multiple threads and swing for displaying status/interaction

    I have a Swing-app which have to show progress and allow userinteraction for these tasks:
    * First:
    retrieve a list of IDs(String) from the database (single thread running)
    * Second:
    some work on the id-list and list written to hd (same thread as above)
    * Third:
    retrieve Objects (based on the id-list) from different sources (Multiple Threads are running)
    To show the status I have a JProgressBar (indeterminate while task1&2 running) and
    a JTextArea showing the current status (connect,retrieve list, sort, ...)
    When task3 is starting the JTextArea have to disappear and be replaced by a ScrollPane
    with an array of Labels/TextAreas showing the status of each thread.
    While theses threads are working, the ID-list will be consumed and the JProgressBar
    shows the remaining precentage of the hole progress.
    Everything is working so far (excepts UI :) , the problem(s) I have:
    I need the threads to interacts with the user through the ui. e.g: "Connection to db-xyz lost! reconnect?"
    But I don&#180;t know how to do this correctly.
    I think one way would be to send an event to the ui... but how?
    (the ui must know which thread is calling to unpause it after user answered)
    I know that threads should NOT change the swing(-container) - How do I notify the ui that a thread has a question?
    Since these threads are really time-consuming the UI is not updated frequently,
    how can I increase this? (perhaps using another thread-priority?)
    thanks for help!

    if/when your threads need to interact with the UI, they can create a Runnable & send it to SwingUtilities.invokeLater or invokeAndWait. This Runnable can popup a message to the user, and act on the choice of the user (reconnect, cancel, ...). This action could be something which "unpauses" the task thread.
    You may need to do synchronisation between the code in the Runnable & the Thread to which it is related - so the latter Thread knows when the user has made the choice.

  • Hangs and crashes when moving from M$ to Sun

    I am currently moving a 50000 lines applet from Microsofts JVM to Sun's. However, on Windows 98 the applet hangs when using the Sun JVM 1.3.X. Of course I have used EventQueue.invokeLater and EventQueus.invokeAndWait to ensure that all updates are handled on the AWT event thread. Further, I have inserted in nearly every routine a test that checks that it is executed on the AWT thread. Thus I am close to certain that it is not due to AWT code being executed on other threads than the AWT event thread.
    Further, when I execute the applet on Sun's JVMV1.4.X it crashes and takes down the browser (IE or Netscape 6.2) too. The crash dumps indicate that this happens in the AWT library, possibly during Event scheduling. However, the program counter of the Intel microprocessor is not valid and thus the JVM cannot make a stack dump.
    What am I doing wrong?

    Sorry for not answering before.
    I have never had a crash on 1.3. I have problems with the Sun JVM 1.3 hanging in Windows 98, but it works fine on Windows 2000. Our tooltips are created from the awt thread, and the tool tip thread calls EventQueue.invokeLater when it wants to remove the tool tip. Thus it the screen is always updated from the awt thread.

  • A question about SwingUtilities.invokeAndWait

    I have this method in my program:
          * Execute the query and closes the dialog
         private void executeQueryAndClose() {
              String whereClause = (String) queryCbo.getSelectedItem();          
              List<JobFields> jobs = controller.getQueryResult(whereClause);
              controller.getEditWindow().getResultsPane().cleanResults();
              controller.getEditWindow().getResultsPane().displayResults(jobs);
              dispose();
         }this method executes a query to the db, display the results and closes
    the query dialog.
    This method is run in the event dispatcher thread.
    Now I was wondering if I should put the controller.getQueryResults in a different thread and run SwingUtilities.invokeAndWait with the new thread.
    I have to wait for the results from the db to return before I can display them,
    but I accomplish the same thing by running it the way written above.
    What's the difference between retrieving the results from the db in the event dispatcher thread and running them in a seperate thread and waiting for them to return by using invokeAndWait?
    In both ways I wait for the results from the db to return.

    I have this method in my program:
          * Execute the query and closes the dialog
         private void executeQueryAndClose() {
    String whereClause = (String)
    g) queryCbo.getSelectedItem();          
    List<JobFields> jobs =
    = controller.getQueryResult(whereClause);
              controller.getEditWindow().getResultsPane().cleanRes
    ults();
              controller.getEditWindow().getResultsPane().displayR
    esults(jobs);
              dispose();
         }this method executes a query to the db, display the
    results and closes
    the query dialog.
    This method is run in the event dispatcher thread.
    Now I was wondering if I should put the
    controller.getQueryResults in a different thread and
    run SwingUtilities.invokeAndWait with the new
    thread.
    I have to wait for the results from the db to return
    before I can display them,
    but I accomplish the same thing by running it the way
    written above.
    What's the difference between retrieving the results
    from the db in the event dispatcher thread and
    running them in a seperate thread and waiting for
    them to return by using invokeAndWait?
    In both ways I wait for the results from the db to
    return.If you do this work in the Event dispatch Thread, you will block all other event related activity from occurring. For example, if you press a button to retrieve the results, the button may seem stuck in the pressed position while the work occurs. This is one of the primary sources of 'preceived slowness' with Swing applications.
    The proper way to do this is the spawn a Thread to do the work, and then use invokeLater (not invokeAndWait) from this spawned Thread to update the UI. I created an example that exhibits the 'bad' and 'good' way to do this. See this post:
    http://forum.java.sun.com/thread.jspa?threadID=743510

  • Wlclient and clusters

    Hi,
    We currently have an issue with the use of wlclient from a Swing app going to a weblogic 8.1 sp4 cluster.
    When the cluster has 2 servers ( our test state ) everyting works fine.
    But when the cluster has 4 servers ( our production environment ) we get random NullPointerExceptions from one one the Weblogic classes.
    The Swing app is started using SwingUtilities.InvokeLater and Security.RunAs. A thread is running doing multiple calls to the same EJB, when the application makes another EJB call from a different thread at the same time, the error appears.
    The stack trace is below.
    java.lang.NullPointerException
         at weblogic.corba.client.security.SecurityInterceptor.receive_reply(SecurityInterceptor.java:192)
         at com.sun.corba.se.internal.Interceptors.InterceptorInvoker.invokeClientInterceptorEndingPoint(InterceptorInvoker.java:274)
         at com.sun.corba.se.internal.Interceptors.PIORB.invokeClientPIEndingPoint(PIORB.java:555)
         at com.sun.corba.se.internal.corba.ClientDelegate.invoke(ClientDelegate.java:457)
         at org.omg.CORBA.portable.ObjectImpl._invoke(ObjectImpl.java:457)
         at ca.gc.ccra.rhmc.tieri.ejb._RHDataCachingBroker_Stub.getString(Unknown Source)
         at ca.gc.ccra.rhmc.tieri.ejb._RHDataCachingBroker_Stub.getString(Unknown Source)
         at ca.gc.ccra.rhmc.tierc.RHRetrieverDelegate.getString(RHRetrieverDelegate.java:790)
         at ca.gc.ccra.nd.nedd.common.interfaces.corpauthority.message.LocalMessageLoader.lookupTextResourceInRH(LocalMessageLoader.java:209)
         at ca.gc.ccra.nd.nedd.common.interfaces.corpauthority.message.LocalMessageLoader.prefetchMessages(LocalMessageLoader.java:159)
         at ca.gc.ccra.nd.nedd.common.interfaces.corpauthority.message.PrefetchMessagesThread.refreshMessages(PrefetchMessagesThread.java:45)
         at ca.gc.ccra.nd.nedd.common.interfaces.corpauthority.message.PrefetchMessagesThread.run(PrefetchMessagesThread.java:29)

    Jean-Francois Cormier <> writes:
    Yeah, its a little strange. By default load-balancing should be sticky
    to avoid stateless reauthentication of every call. You might want to
    see if sp5 helps at all (both client and server). I know there was a
    bug fixed in either there or sp4 wrt reauthentication.
    andy
    Thanks,
    Here some other info, i've set the weblogic.debug.client.security flag to true. It seems as if it's re-authenticating for each call. This only happens in our production environement ( siteminder plugin for security ). If I run against my own cluster with a vanilla file realm it works ok.
    We will probably end up having to raise a case or go back to weblogic.jar.
    Here's some of the debuging output, it looks like there is always an invalid context, maybe that's why a NullPointer is thrown:
    <SecurityInterceptor> send_request(<5ac0bced>.create)
    <SecurityInterceptor> adding MessageInContext
    <SecurityInterceptor> receive_exception(create)
    <SecurityInterceptor> found SAS ContextError for create()
    <SecurityInterceptor> client context not valid, retrying
    <SecurityInterceptor> send_request(<bac8a6ee>.create)
    <SecurityInterceptor> adding security context from 1 components for Subject:
         Principal: CCRAPrincipal "prezeau"
         Private Credential: weblogic.security.auth.login.PasswordCredential@1a1399
         Private Credential: SubjectProxy[23032071]
    <SecurityInterceptor> receive_reply(create)
    <SecurityInterceptor> found SAS context for create()
    <SecurityInterceptor> send_request(<f5c5ddfd>.getString)
    <SecurityInterceptor> adding MessageInContext
    <SecurityInterceptor> receive_exception(getString)
    <SecurityInterceptor> found SAS ContextError for getString()
    <SecurityInterceptor> client context not valid, retrying
    <SecurityInterceptor> send_request(<81007eb6>.getString)
    <SecurityInterceptor> adding security context from 1 components for Subject:
         Principal: CCRAPrincipal "prezeau"
         Private Credential: weblogic.security.auth.login.PasswordCredential@1a1399
         Private Credential: SubjectProxy[23032071]
    <SecurityInterceptor> receive_reply(getString)
    <SecurityInterceptor> found SAS context for getString()
    <SecurityInterceptor> send_request(<4a952556>.create)
    <SecurityInterceptor> adding MessageInContext
    <SecurityInterceptor> receive_exception(create)
    <SecurityInterceptor> found SAS ContextError for create()
    <SecurityInterceptor> client context not valid, retrying
    <SecurityInterceptor> send_request(<7f3c180e>.create)
    <SecurityInterceptor> adding security context from 1 components for Subject:
         Principal: CCRAPrincipal "prezeau"
         Private Credential: weblogic.security.auth.login.PasswordCredential@1a1399
         Private Credential: SubjectProxy[23032071]
    <SecurityInterceptor> send_request(<157197b9>.resolve_any)
    <SecurityInterceptor> adding security context from 1 components for Subject:
         Principal: CCRAPrincipal "prezeau"
         Private Credential: weblogic.security.auth.login.PasswordCredential@1a1399
         Private Credential: SubjectProxy[23032071]

  • Problem with Thread in JApplet

    Hi,
    I am working on a project on pseudo random functions, and for that matter I have written a problem. Now I am working on a user interface (JApplet) for my program. Because some heavy calculations can occur, I want to keep track of the progress, and show that in my JApplet. To do so, I start a Thread in which the calculations take place. In my JApplet I want to show every second how far the proces is done. The strange thing is, that the status JLabel only appears when the whole proces is done, and the start button keeps pressed during the proces. If I run this in the applet viewer, I can see the status every second in my command box. You can see the applet here : applet
    The code concerning the start button's actionlistener (entire appletcode: [applet code|http://www.josroseboom.nl/PseudoRandomClusteringApplet.java]) :
              if(e.getSource()==start)
                   int[][] randomFuncties = new int[current+1][5];
                   int puntenHuidige, g, q, y, m, f;
                   boolean done;
                   Kern k;
                   for(int i = 0;i<=current;i++)
                        randomFuncties[i] = functies.getValues();
                   invoer.remove(knopjes);
                   startTijd = System.currentTimeMillis();
                   proces.setBounds(25,(current+4)*25, 2*this.getWidth()/3,75);
                   invoer.add(proces);
                   this.validate();
                   this.repaint();
                   for(int i = 0;i<=current;i++)
                        puntenHuidige = 0;
                        f = randomFuncties[i][0]; // important for instantiation of k, which is cut out here
                        done = false;
                        k.start();     // k is a Thread where heavy calculations are done
                        ((JLabel)(proces.getComponent(2))).setText("points done of current (" + q + ")");
                        this.repaint();
                        while(!done)
                             ((JLabel)(proces.getComponent(1))).setText("" + convertTime(System.currentTimeMillis() - startTijd));
                             ((JLabel)(proces.getComponent(3))).setText("" + k.getPuntenGehad()); // get the point done so far
                             ((JLabel)(proces.getComponent(5))).setText("" + ((100*k.getPuntenGehad())/q) + "%");
                             debug("q: " + q);
                             debug("point done: " + k.getPuntenGehad());
                             if(k.getPuntenGehad()==q)     //if all points are considered
                                  done=true;
                             this.validate();
                             this.repaint();
                             try
                                  Thread.sleep(1000);
                             catch(InterruptedException exception)
                                  debug("foutje met slapen: InterruptedException");
                             catch(IllegalMonitorStateException exception)
                                  debug("foutje met wachten: IllegalMonitorStateException");
                             debug("IN APPLET: yet another loop walk");
                        stringResultaten.add(k.geefResultaat());
                   klaarLabel.setBounds(this.getWidth()/4,(current+8)*25, this.getWidth()/2,25);
                   naarResultaat.setBounds(25+this.getWidth()/4,(current+9)*25, this.getWidth()/4,25);
                   invoer.add(klaarLabel);
                   invoer.add(naarResultaat);
                   this.validate();
                   this.repaint();
    Edited by: Jos on Sep 19, 2007 1:22 AM

    Never do anything that takes more than a fraction of a second in an actionPerformed method or similar GUI callback.
    The GUI stuff is all handled by a single thread called the "AWT Dispatcher" thread. That includes code in such callbacks. While it's executing your callback it can't do any kind of screen updating or response to other user events.
    Instead your actionPerformed should work with a separater "worker" thread, either it should launch a new thread, or release one you create (using wait and notify). Then, it returns without waiting. When the worker thread wants to update the GUI it uses EventQueue.invokeLater() or invokeAndWait() to run some (fast) code on the Dispatcher thread.

  • Right way to fire table changes

    suppose i have a class that extends AbstractTableModel and i used a List to store data, like
    public class MyTableModel extends AbstractTableModel
    List dataList = Collections.synchronizedList(new LinkedList());
    public void insertMyData(String data)
    synchronized(dataList)
    // ... do something
    ##Line A##
    ##Line B##
    If i want to fire table changes, say like using
    this.fireTableDataChanged();
    where should i place it?
    at ##Line A## or ##Line B## ???
    or should I use
    SwingUtilities.invokeLater(new Runnable(){public void run(){
      this.fireTableDataChanged();
    Moreover, i would like to ask, if I implement my own TableCellRender and overriding the getTableCellRendererComponent method, all the calls like setText, setBackground, setForeground,...
    should i use SwingUtilities.invokeLater to do that? or just call it as usual ?
    Thanks alot

    Since you mention synchronized several times, I assume your model will be accessed from different threads
    (although you didn't write this.) Client code will have to be careful: getRowCount may return 10, but by the
    time the client gets to row 7 it may no longer exist! What does your model do when getValueAt is based
    indices that are out of bounds?
    As far as synchronization goes, I think you are going overboard with:
    List dataList = Collections.synchronizedList(new LinkedList());...since you are using synchronization blocks elsewhere. In general, I find little use for those synchronizedXXX
    factory methods -- usually the class having a collection member provides the thread safety.
    As far as the listeners go, model listeners assume their event handlers are executing in the EDT, so
    you will have to call the fire*** methods from the EDT. This means you have to use invokeLater or invokeAndWait.
    Using invokeAndWait defeats the multithreading you are building, so I think you
    should call invokeLater, and since this is an asynchronous-style call it makes no sense doing it
    from within a synchronized block. Just be aware that your JTable class may quety the model
    out of bounds.
    Also, if your model's data is written or changed seldom but read often, I would use the serial immutable
    pattern. Have the List reference dataList point to list whose state is immutable. If you want to change
    the data, you make a copy, change that and then have dataList refer to the updated copy.

  • JLabel in a JFrame delayed Rendering. How do i render first then continue?

    i have a snippent of code:
    JDialog msg_window;
         public void create_window(JPanel contentPane, JLabel jLabel1) {
              msg_window= new JDialog();
              contentPane=(JPanel)msg_window.getContentPane();
              contentPane.setLayout(null);
              jLabel1.setBounds(48,16,133,18);
              contentPane.add(jLabel1);
              msg_window.setContentPane(contentPane);
              msg_window.setSize(222,85);
              msg_window.setLocation(300,252);
              msg_window.setTitle(jLabel1.getText());
              msg_window.setVisible(true);
    that creates a JDialog box. My intentions are to display this dialog box while another part of the program is attempting to load the JTDS database driver. The driver loading seems to temporarily distract the VM. What happens is the box will render, but the JLabel will not until the driver is loaded ( at which point the box disapears).
    How can i make sure the JDialog and all it's components fully rendered before proceding with then next step in the program?

    This example just uses the extra thread to burn cpu cycles and updat a JLabel on the dialog, but shows interaction between modal dialog and an external thread.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class LoadDialog extends JDialog
        JLabel statusLbl;
        public LoadDialog(JFrame parent )
            super( parent );
            setTitle("Loadinig ");
            JPanel cp = new JPanel();
            cp.setLayout( new BorderLayout());
            cp.add( new JLabel("Please Wait") , BorderLayout.NORTH );
            statusLbl = new JLabel("Counter =     ");
            cp.add( statusLbl, BorderLayout.SOUTH );
            setContentPane( cp );
            pack();
            Runnable runner = new Runnable()
                public void run()
                    for( int i = 0; i < 1000000; i++ )
                        for( int j = 1; j < 1000; j++ )
                            int x = 200 * i / j;
                        final int count = i;
                        try
                            SwingUtilities.invokeAndWait( new Runnable()
                                                              public void run()
                                                                  statusLbl.setText( "Counter = "+count );
                        catch( Exception exc )
                            exc.printStackTrace();
            setModal( true );
            Thread t = new Thread( runner );
            t.start();
            setLocationRelativeTo( parent );
            setVisible( true );
        public static void main(String[] args) throws Exception
            try
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            catch( Exception e )
            final JFrame f = new JFrame("Threaded Dialog");
            JPanel cp = new JPanel();
            JButton button = new JButton( "Load");
            cp.add( button );
            button.addActionListener( new ActionListener()
                                          public void actionPerformed( ActionEvent e )
                                              new LoadDialog( f );
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.setContentPane(cp);
            f.pack();
            f.setLocationRelativeTo(null);
            f.setVisible(true);
    }For your problem, you I would recommend you thread off the file load and use invokeLater or invokeAndWait to dismis the dialog and pass the loaded file back to the main app.
    Hope this helps,
    Todd

Maybe you are looking for

  • Error in Receiver FCC: Unknown structure ... found in document

    Hi Experts, I have a problem with the Receiver File Adapter. I want to use Content Conversion to generate a plain file. Input to receiver file adapter: <?xml version="1.0" encoding="utf-8" ?> <PlainFile>   <filename>filename.txt</filename>   <line>Li

  • IPhoto misbehaving - can't edit

    I can't edit an album full of raw images. iPhoto is set to keep my files in my Finder folder structure. If I right click a file to reveal the underlying file it shows me the jpeg in the modified folder in the iPhoto library. But it doesn't seem to be

  • Items not appearing in cascading dynamic list

    Hi I am having an issue with cascading prompts in Crystal Reports 2008. I have two cascade levels in this report. The report worked fine for a few months until we recently noticed some items were not showing up on the first list. In the database, the

  • GeForce 7300 GT with more than 2GB RAM?

    I had a lot of crashes with my MP and had original 2x512MB & Kingston's 2x1GB installed. I contacted Kingston's support when Rember caused kernel panic every time I tried to test memory with it. They said that it is "known issue" that 7300gt does not

  • No printers found on ipod touch?

    I pad/ipod touch won't find printer in spite of wireless and ePrint lights on on HP Deskjet 3070A?