Running another thread not to block UI

I do some heavy operation inside the actionPerformed (load images from File Chooser, resize it for display and populate it in the ScrollPane etc) and I realize that the windows freezes until the whole operation is finished. And it doesn't really help that I do repaint() or validate(). I make some research and some of the books and people from forums say that I actually needed to dispatch another thread to run the heavy operation. So that I won't block the UI interface and can update things accordingly. But the problem is, I don't have any clear example to understand this concept. How to clean up the thread after operation finished. How can a thread notify the progress back and etc. I need to know how much images has been loaded so that I can update the progress bar and so on. Can anyone help me point out a good example? :D

Think I should show my code snippet to you
public void actionPerformed(ActionEvent e) {
        if (e.getSource() == BtnBrowse) {
            int returnVal = fcSelectFile.showDialog(this,"Select");
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                file= fcSelectFile.getSelectedFiles();
                //This is where a real application would open the file.
                Thread worker=new Thread(){
                        public void run(){
                            int count=0;
                            selectedFile=new JLabel[file.length]; 
                            while(count<file.length)
                            {   final int index=count;
                                String actualFile=file[count].toString();
                                String fileName= file[count].getName();
                                selectedFile[count]=new JLabel(createImageIcon(actualFile,fileName));
                                SwingUtilities.invokeLater(new Runnable(){
                                public void run(){
                                PnlImageHolder.add(selectedFile[index]);
                                PnlImageHolder.repaint();
                                PnlImageHolder.validate();
                                count++;
                worker.start();
                ScpImageScroller.getViewport().add(PnlImageHolder);
}

Similar Messages

  • Close a blocking wait thrad by another thread

    Hi all
    I have a lookup method which makes a blocking wait and I want to close this lookup if the content not available for 10 seconds.
    What I have done is put this lookup in a thread(LookupThread) and used separate thread(TimeCheckThread) for calculate the elapsed time.
    This is my idea
    public class LookupThread extends Thread
        Calendar cal = Calendar.getInstance();
        boolean closed = false;
        public TimeCheckThread getTimeChecker()
            return new TimeCheckThread();
        public void run()
            lookMethod(); // this is the blocking wait
        public class TimeCheckThread extends Thread
            long startTime = cal.getTimeInMillis();
            public void run()
                // strted looking for elapsed time
                while(true)
                    cal = Calendar.getInstance();
                    if(cal.getTimeInMillis()-startTime > 10000 & !closed)
                        // if 10 seconds elapsed close the thread which makes the blocking wait
                        LookupThread.super.stop();
                        closed = true;
                        // to exit from time check thread
                        break;
        public static void main(String args[])
            LookupThread v = new LookupThread();
            v.getTimeChecker().start();
            v.start();
    }The problem is closing of thread is deprecated.
    LookupThread.super.stop();So any idea to handle those blocking wait situations and assign a return time other than this approach?

    WirajR wrote:
    Also TimeCheckThread eats of CPU time for 10 seconds use a java.util.Timer instead
    >Also TimeCheckThread eats of CPU time for 10 seconds use a java.util.Timer instead
    Hi
    I think this is the most suit to my requirement. Totally different way, but acceptable.
    To EJP
    Ur solution seems great to replace following code segment
    public class TimeCheckThread extends Thread
            long startTime = cal.getTimeInMillis();
            public void run()
                // strted looking for elapsed time
                while(true)
                    cal = Calendar.getInstance();
                    if(cal.getTimeInMillis()-startTime > 10000 & !closed)
                        // if 10 seconds elapsed close the thread which makes the blocking wait
                        LookupThread.super.stop();
                        closed = true;
                        // to exit from time check thread
                        break;
        }like following
    public class TimeCheckThread extends Thread
           public void run()
                        TimeCheckThread.sleep(10000);
                        LookupThread.super.stop();
    }To Peter__Lawrey
    Why don't you make the blocking lookup block for only 10 seconds?Any idea to implement such blocking lookup block?
    My blocking operation is a looking for RTP video stream. It waits until server sends the video

  • When I try to start Firefox, I get a message that it is already running but not responding and I can't run another Firefox at the same time. I uninstalled and reinstalled. No change. Tried various other suggestions. Help!!

    When I try to start Firefox, I get a message that it is already running, but not responding and that I should close it before trying to run another Firefox. But I cannot find a way to close Firefox program that is not running as far as I can see. I tried uninstalling and reinstalling Firefox, but that did not work. I've tried various other things, but no luck. I thought programs should stop when the computer is turned off, but that didn't work either.

    How are you opening the Profile Manager?
    *http://kb.mozillazine.org/Profile_Manager
    Sounds that Firefox is still or already running.<br />
    See:
    *http://kb.mozillazine.org/Kill_application

  • TS3212 I am trying to install itunes on my pc and the run window will not appear. I changed the pop-up blocker settings and I still can't see it?

    I am trying to install itunes for my pc and the run window will not come up and I have changed my pop-up blocker settings and it still will not appear.....help?

    I'd first try downloading an installer from the Apple website using a different web browser:
    http://www.apple.com/quicktime/download/
    If you use Firefox instead of IE for the download (or vice versa), do you get a working installer?

  • Animation is not a thread and therefore blocking my view

    Hi,
    I have a small animation on my view, but it seems, that as long this animation is running, I am not able to use my view (for example the buttons..)
    - (void) showInfoAsThread:(NSString*) info{
    NSAutoreleasePool *pool = [NSAutoreleasePool new];
    if(animating == FALSE){
    infoView = [[RoundedRectView alloc] initWithFrame:CGRectMake(50.0,327.0, 210.0, 30)];
    UILabel *infoLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 5, 200, 18)];
    infoLabel.backgroundColor = [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.0];
    infoLabel.text = info;
    [infoLabel setTextAlignment:UITextAlignmentCenter];
    [infoLabel setTextColor:[UIColor darkGrayColor]];
    infoLabel.font = [UIFont boldSystemFontOfSize:14];
    [infoView addSubview:infoLabel];
    [infoLabel release];
    [self.view addSubview:infoView];
    [UIView beginAnimations:@"fadeOut" context:NULL];
    [UIView setAnimationDelegate:self];
    [UIView setAnimationDidStopSelector:@selector(loadingViewDisappear:finished:context:)];
    [UIView setAnimationDuration:2];
    [infoView setAlpha:0];
    animating = TRUE;
    [UIView commitAnimations];
    [pool release];
    what i am doing wrong? should i just write my own UIView and make it changing its opaque values in a thread?

    Not that I have a solution or anything but has anyone actually filled out a feedback form about this?
    http://www.apple.com/feedback/
    Apple can't fix what they don't know. Complaining here does not help, this forum is not monitored by Apple.
    If you haven't found a solution yet (I'm still searching too), then please file a feedback and continue to do so. The more feedback Apple receives, the more attention it will get. Hopefully.

  • Why does Firefox give this message when I do not have another program running "Firefox is already running, but is not responding. To open a new window, you must first close the existing Firefox process, or restart your system."

    Question
    why does Firefox give this message when I do not have another program running or another window open - "Firefox is already running, but is not responding. To open a new window, you must first close the existing Firefox process, or restart your system." edit

    See also "Hang at exit":
    *http://kb.mozillazine.org/Firefox_hangs
    *https://support.mozilla.com/kb/Firefox+hangs

  • Can I run another Small Basic program from a simple menu in another Small Basic program, (It does not need to return!)

    Hi
    Is there a way of calling another program from within a small basic program ?
    I dont mean run within it and then continue where it left off.
    I simply ideally I ideally want to create one program that only contains menu options and depending on the user choice, then to go off and run another program.
    If this is not possible..maybe I am getting over cautious, but does any one know the program size limit, if I need to put all teh features in one program ?
    Thanks in advance
    Dave

    You would need an extension that can start an external exe (may be any exe includng another pre-compiled Small Basic program, or even the SmallBasicComplier to compile source and then run it), such as LDProcess.Start in my extension.  There are also
    other extensions with this or similar commands.

  • I get a message that "firefox is running another in the background and should be shut down before another can run OR restart your computer" I get this even when there is not another firefox running in the background. Any suggestions to fis this issue?

    No more details other than above . I have uninstalled and re-installed FIREFOX several times and still get this issue. Also, very slow in connecting to websites.

    See:
    * http://kb.mozillazine.org/Profile_in_use
    * https://support.mozilla.com/kb/Firefox+is+already+running+but+is+not+responding

  • Thread not running ?

    hi everyone :)
    im trying to make a multithreaded producer / consumer with stack as a shared recourse.
    the below code compiles fine ( in JCreator ), but when i run it i get "press any key to continue..." instead of the expected "pushed" "popped"......
    does anyone have an idea what it wrong.... im lost :)
    thanks in advance
    class Buffer {
         private final int MAX_BUFFER_SIZE = 16;
         private int buffer[] = new int[ MAX_BUFFER_SIZE ];
         private int no_in_buffer=0;
         public void push( int i ) {
              try {
                   if( no_in_buffer == MAX_BUFFER_SIZE ) {
                        throw (new Exception("ErrorBufferFull"));
                   } else {
                        System.out.println( "Pushed" );
                        buffer[no_in_buffer++] = i;
              } catch( Exception e ) {
                        System.err.println(e.getMessage());
                        e.printStackTrace();
         public int pop() {
              try {
                   if( no_in_buffer == 0 ) {
                        throw (new Exception("ErrorBufferEmpty"));
                   } else {
                        System.out.println( "Popped" );
                        return buffer[no_in_buffer--];
              } catch( Exception e ) {
                        System.err.println(e.getMessage());
                        e.printStackTrace();
                        return 0;
    class Consumer implements Runnable {
         protected Thread execution;
         private Buffer buffer;
         public Consumer( Buffer r ) {
              buffer = r;     
         public synchronized void begin() {
              if(execution == null ) {
                   System.out.println( "Consumer begin() called" );
                   execution = new Thread( this );
                   execution.setPriority( Thread.MIN_PRIORITY );
                   execution.start();     
         public synchronized void end() {
              if( execution != null ) {
                   execution.interrupt();
                   execution = null;     
         public void run() {
              try {
                   Thread myself = Thread.currentThread();
                   while( execution == myself ) {
                        System.out.println( "Consumer running" );
                        buffer.pop();
              } finally {
                   synchronized( this ) {
                        execution = null;     
    class Producer implements Runnable {
         protected Thread execution;
         private Buffer buffer;
         public Producer( Buffer r ) {
              buffer = r;     
         public synchronized void begin() {
              if(execution == null ) {
                   System.out.println( "Producer begin() called" );
                   execution = new Thread( this );
                   execution.setPriority( Thread.MIN_PRIORITY );
                   execution.start();     
         public synchronized void end() {
              if( execution != null ) {
                   execution.interrupt();
                   execution = null;     
         public void run() {
              try {
                   Thread myself = Thread.currentThread();
                   while( execution == myself ) {
                        System.out.println( "Producer running" );
                        buffer.push( (int) Math.random() % 10 );
              } finally {
                   synchronized( this ) {
                        execution = null;     
    class App {
         public static void main( String args[] ) {
              Buffer r = new Buffer();
              Producer p = new Producer( r );
              Consumer c = new Consumer( r );
              p.run();
              c.run();

    You should start your threads using start () instead of run ().
    Kind regards,
    Levi

  • Are you suppose to access UIView from another thread?

    A lot of UI events in my apps take place in another thread. So in my uivewcontroller, it catches a button click for example, it launches a NSThread with some parameter. The reason I decided to use a thread is because if the duration takes long the UI completely locks up. The thread then fetches for some result and access a pointer to a UIView (a UILabel for example) and update it's content.
    Now, is this model correct? I'm running in cases where setting the UILabel.text from the thread sometimes work, sometimes doesnt. I'm not sure how to debug. If I change the thread call to a standard method call (which blocks until results are ready) the text is updated correctly.
    Any hints?

    http://developer.apple.com/documentation/Cocoa/Conceptual/Multithreading/ThreadS afetySummary/chapter950_section2.html

  • Scheduled thread pools and blocking

    Hello,
    I am using a scheduled thread pool created in the following way:
    ScheduledExecutorService scheduler = Executors.newScheduledThreadPool();I want to schedule a task on the scheduler, but this task uses a MulticastSocket and can block on:
    byte[] b = new byte[BUFFER_LENGTH];
    DatagramPacket dgram = new DatagramPacket(b, b.length);
    socket.receive(dgram);Say I schedule this code to run at 500 ms. The first run blocks on the receive method. If the block lasts for more that 500ms, what happens when the scheduler allocates another thread at the next 500ms mark? Can I "lose" a thread from the pool permanently? Can I cause a backup of multiple threads blocking every time the scheduler runs the task?
    Thanks!
    -pm

    Well it used to be a plain old Runnable with the receive() inside the run() method, and the runnable was launched inside a Thread. However, I have an infrastructure that adds tasks to a ScheduledExecutorService so that I can run tasks that require a timing mechanism. I also have an ExecutorService for executing tasks at one time. I want to use these concurrency facilities to get this task to always run, not just once, and I thought scheduling would allow that. Would the ExecutorService's submit() method do that? Would it make more sense to have the run() method loop:
    run(){
    byte[] b = new byte[BUFFER_LENGTH];
    DatagramPacket dgram = new DatagramPacket(b, b.length);
    while(true){
    socket.receive(dgram);
    // do something ...
    }and then have ExecutorService simply run execute()?
    Thanks!

  • Killing an exec'ed process from another thread

    Hi all,
    I written an application that executes some external OS - processes. There is a dispatcher thread, that starts the execution threads for some jobs. Every execution thread creates a Processes by calling runtime.exec(), adds this object to a TreeMap ( member of the dispatcher ), creates two threads for reading the output of the process ( sdtout & stderr ) and calls p.waitFor(). From this moment this thread is blocked. After the process is done, the results will be processed by this thread etc. Now I want to go ahead and let the application user kill the process. For them I let the dispatcher - thread, that has also a reference to the executed process to call destroy of it if necessary during the execution thread is blocked by waitFor() and two output threads are reading stdout & stderr. The problem is however that destroy() - call from another thread doesn't kill the subprocess. The subprocess is running until it's done or terminated from out of jvm. Have you an idea or example?
    Thanks a lot & regards
    Alex

    >
    I know you have been discussing your problem is that
    you can't kill a "sleep" process. But just to be
    sure, I tested your description by one thread exec-ing
    a "not-sleep" program, and then another thread had no
    trouble killing it.
    I took your code and wrote a program around it such
    that
    Thread1 :
    - creates a Job (but not a "sleep" job); creates a
    JobMap ; puts Job in JobMap
    - starts Thread2 (passing it JobMap)
    - sleeps 15 seconds
    - calls Job.kill() (your method)
    Thread2 :
    - gets Job from JobMap
    - calls Job.execute() (your method)
    It's quick and dirty and sloppy, but it works. The
    result is when the kill takes place, the execute
    method (Thread2) wakes from its waitFor, and gets
    exitValue() = 1 for the Process.
    so,
    In order to kill the sleep process, which (according
    to BIJ) is not the Process that you have from exec
    call, maybe the only way to kill it is to get its PID
    an exec a "kill -9" on it, same as you said you had to
    do from the commandline. I don't know if you can get
    the PID, maybe you can get the exec-ed process to spit
    it onto stdout or stderr?
    (I am on win, not *nix, right now, so I am just
    throwing out a suggestion before bowing out of this
    discussion.)
    /MelHi Mel,
    yes, it should work right on windows because you created probably the shell by cmd /c or something like this. If you kill the cmd - process, everithing executed by the interpretter will be killed too. My application is running on Windows and unix. On unix I have to execute the process from a shell ( in my case it is the born shell ). The problem is however, that the born shell has another behaviour as cmd and doesn't die. Do you have an idea how to get the pid of the process started by sh without command line? To kill the processes from the command line is exactly what my customers do now. But they want to get "a better service" ...:-)
    Regards
    Alex

  • How can I pass an exception from one thread to another thread

    If I create a new class, that will extends the class Thread, the methode run() can not be use with the statement Throws Exeption .
    The question now: Is there any possibility to pass an exception from one thread to another thread?
    Thx.

    It really depends on what you want to do with your exception. Is there some sort of global handler that will process the exceptions in some meaningful way? Unless you have that, there's not much point in throwing an exception in a thread, unless you simply want the stack trace generated.
    Presuming that you have a global handler that can catch exceptions, nest your Exception subclass inside a RuntimeException:
    public class NestedRuntimeException extends RuntimeException
        private final m_nestedException;
        public NestedRuntimeException(final Exception originalException)
            super("An exception occurred with message: " + originalException.getMessage());
            m_nestedException;
        public Exception getNestedException()
            return m_nestedException;
    }Your global handler can catch the NestedRuntimeException or be supplied it to process by the thread group.

  • Error : FRM-41211 : Integration Error: SSL Failure Running Another Product

    Hi All
    I am using Forms & Reports 10g.
    I have a report .And i am trying to call in my forms and also i am passing parameters.
    But i am getting this error :
    My Code is :-
    DECLARE
    repid REPORT_OBJECT;
    v_rep VARCHAR2(100);
    rep_status VARCHAR2(20);
    plid ParamList;
    vParamValue number;
    BEGIN
    plid := Get_parameter_List('tmp');
    IF NOT Id_Null(plid) THEN
    Destroy_parameter_List( plid );
    END IF;
    plid := Create_parameter_List('tmp');
    Add_Parameter(PLid, 'P_Block', Text_Parameter, :block_query.item_block);
    Add_Parameter(PLid, 'P_Category', Text_Parameter, :block_query.item_category);
    Add_Parameter(PLid, 'P_Dept', Text_Parameter, :block_query.item_dept);
    Add_Parameter(PLid, 'P_Floor', Text_Parameter, :block_query.item_floor);
    Add_Parameter(PLid, 'P_IP', Text_Parameter, :block_query.item_ip);
    Add_Parameter(PLid, 'P_Room', Text_Parameter, :block_query.item_room);
    Add_Parameter(PLid, 'P_Userid', Text_Parameter, :block_query.item_usr_id);
    Add_Parameter(PLid, 'PARAMFORM', Text_Parameter, 'NO');
    repid := FIND_REPORT_OBJECT('REPORT_Query');
    SET_REPORT_OBJECT_PROPERTY(repid,REPORT_COMM_MODE,SYNCHRONOUS);
    SET_REPORT_OBJECT_PROPERTY(repid,REPORT_DESTYPE,cache);
    SET_REPORT_OBJECT_PROPERTY(repid,REPORT_DESFORMAT,'PDF');
    SET_REPORT_OBJECT_PROPERTY(repid,REPORT_OTHER, 'paramform=no');
    v_rep := RUN_REPORT_OBJECT(repid,plid);
    rep_status := REPORT_OBJECT_STATUS(v_rep);
    WHILE rep_status in ('RUNNING','OPENING_REPORT','ENQUEUED')
    LOOP
    rep_status := report_object_status(v_rep);
    END LOOP;
    WEB.SHOW_DOCUMENT('http://A_F2_ITT_PC_4.AAHOS.LOCAL:8890/reports/rwservlet/getjobid'||substr(v_rep,instr(v_rep,'_',-1)+1)||'?
    *'||'server=Report_server_name&P_parameter='||'&block='''||:block_query.item_block*
    *||'&category_name='''||:block_query.item_category*
    *||'&dept='''||:block_query.item_dept*
    *||'&floor='''||:block_query.item_floor*
    *||'&ip_address='''||:block_query.item_ip*
    *||'&room='''||:block_query.item_room*
    *||'&usr_id='''||:block_query.item_usr_id*
    *||'&paramform=no');*
    End;
    And the error i am getting is :- FRM-41211 : Integration Error: SSL Failure Running Another Product

    hi
    please try something like this.
    DECLARE
    repid REPORT_OBJECT;
    v_rep VARCHAR2(100);
    rep_status VARCHAR2(20);
    plid ParamList;
    vParamValue number;
    BEGIN
    plid := Get_parameter_List('tmp');
    IF NOT Id_Null(plid) THEN
    Destroy_parameter_List( plid );
    END IF;
    plid := Create_parameter_List('tmp');
    add_parameter(plid,'p_parameter',text_parameter,to_char(:block.item));
    Add_parameter(plid, 'PARAMFORM', TEXT_parameter, 'NO');
    repid := FIND_REPORT_OBJECT('REPORT6');
    SET_REPORT_OBJECT_PROPERTY(repid,REPORT_COMM_MODE,SYNCHRONOUS);
    SET_REPORT_OBJECT_PROPERTY(repid,REPORT_DESTYPE,cache);
    SET_REPORT_OBJECT_PROPERTY(repid,REPORT_DESFORMAT,'PDF');
    SET_REPORT_OBJECT_PROPERTY(repid,REPORT_OTHER, 'paramform=no');
    v_rep := RUN_REPORT_OBJECT(repid,plid);
    rep_status := REPORT_OBJECT_STATUS(v_rep);
    WHILE rep_status in ('RUNNING','OPENING_REPORT','ENQUEUED')
    LOOP
    rep_status := report_object_status(v_rep);
    END LOOP;
    /*Display report in the browser*/
    WEB.SHOW_DOCUMENT('http://Machine_Name:8889/reports/rwservlet/getjobid'||substr(v_rep,instr(v_rep,'_',-1)+1)||'?
    '||'server=repserver&P_parameter='||:block.item||
    '&paramform=no');
    END;

  • How to refresh a JTable of a class from another thread class?

    there is an application, in server side ,there are four classes, one is a class called face class that create an JInternalFrame and on it screen a JTable, another is a class the a thread ,which accept socket from client, when it accept the client socket, it deal the data and insert into db,then notify the face class to refresh the JTable,but in the thread class I used JTable's revalidate() and updateUI() method, the JTable does not refresh ,how should i do, pls give me help ,thank you very much
    1,first file is a class that create a JInternalFrame,and on it there is a table
    public class OutFace{
    public JInternalFrame createOutFace(){
    JInternalFrame jf = new JInternalFram();
    TableModel tm = new MyTableModel();
    JTable jt = new JTable(tm);
    JScrollPane jsp = new JScrollPane();
    jsp.add(jt);
    jf.getContentPane().add(jsp);
    return jf;
    2,the second file is the main face ,there is a button,when press the button,screen the JInternalFrame. there is also a thread is beggining started .
    public class MainFace extends JFrame implements ActionListener,Runnable{
    JButton jb = new JButton("create JInternalFrame");
    jb.addActionListener(this);
    JFrame fram = new JFrame();
    public void performance(ActionEvent e){
    JInternalFrame jif = new OutFace().createOutFace(); frame.getContentPane().add(JInternalFrame,BorderLayout.CENTER);
    public static void main(String[] args){
    frame.getContentPane().add(jb,BorderLayout.NORTH);
    frame.pack();
    frame.setVisible(true);
    ServerSokct ss = new ServerSocket(10000);
    Socket skt = ss.accept()'
    new ServerThread(skt).start();
    3.the third file is a thread class, there is a serversoket ,and accept the client side data,and want to refresh the JTable of the JInternalFrame
    public class ServerThread extends Thread{
    private skt;
    public ServerThread(Sokcet skt){
    this.skt = skt;
    public void run(){
    OutputObjectStream oos = null;
    InputObjectStream ios = null;
    try{
    Boolean flag = flag;
    //here i want to refresh the JTable,how to write??
    catch(){}
    4.second is the TableModel
    public class MyTableModel{
    public TableModel createTableModel(){
    String[][] data = getData();
    TableModel tm = AbstractTableModel(
    return tm;
    public String[][] getData(){
    }

    Use the "code" formatting tags when posting code.
    Read this article on [url http://www.physci.org/codes/sscce.jsp]Creating a Simple Demo Program before posting any more code.
    Here is an example that updates a table from another thread:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=435487

Maybe you are looking for