Clean dispose a thread

Hi,
I am trying to cleanly dispose from a thread after it's completed it's execution. However I see the activeCount in ThreadGroup increase with each new request. i,e the old threads are not being disposed after it's completetion.
I am using JDK1.3 on HPUX PA RISC server.
This is the code I have written to cleanly exit from thread
public void run()
      while( exitFlag == false )
       this.startFirmwareUpload();
          synchronized(waitOnIPDBSession)
            try {
                    waitOnIPDBSession.wait();
            catch( Exception e ) { }
      if ( exitFlag == true ) {
           // Clean up the thread when done
                 // Exit from run method
                 System.out.println("Cleanly exiting from thread...");
           return;
     * Cleanly close a working thread
    public synchronized void processExitThread()
        // Set exitFlag variable to true
        this.exitFlag = true;
        // Remove unique entry from Map
        ftpHandlerList.remove(waitOnIPDBSession);
    }After each new thread completes it's execution, I am calling "processExitThread" method. However the "exitFlag" in "run" method is not being set to false, so the "run" method never exits from the infinite loop.
Any suggestions to cleanly exit/dispose from a thread are welcome.
Thanks
S

Hi,
  Thread.interrupt()  did the trick. Now the thread is being destroyed after it's completion.My current implementation is this
private boolean exitFlag;
public void run()
    while( this.exitFlag == false )
       this.startFirmwareUpload();
          synchronized(waitOnIPDBSession)
             try {
                     waitOnIPDBSession.wait();
               catch (InterruptedException e)  {
                this.exitFlag = true;
     if (this.exitFlag == true) {
           // Clean up the thread when done
           return;
     * Cleanly close a working thread
    public synchronized void processExitThread()
      ftpHandlerList.remove(waitOnIPDBSession);
      Thread.currentThread().interrupt();
    }Do you think this would be a better implementation, in terms of safety of the application:
public void run()
   while ( true )
         boolean b = Thread.currentThread().isInterrupted();
         if ( !b )
               // Thread not interrupted
               this.startFirmwareUpload();
               synchronized(waitOnIPDBSession)
                   try {
                     waitOnIPDBSession.wait();
                 catch (InterruptedException e)  {
                   this.exitFlag = true;
         else {
               // Thread is interrupted
               this.exitFlag = true;
       if ( this.exitFlag == true ) {
           break;   // Exit from while loop
     } // End of While loop
   return;
}Any feedback welcome.
Thanks
S

Similar Messages

  • GC Cause: 'Artifical: Cleaning up Finished Threads' (strange behaviour)

    Hi everybody,
    we have experiencing an strage issue after increasing our heap size and nursery in Production from
    -Xms2816M -Xmx2816M -Xns550M to -Xms4096M -Xmx4096M -Xns1024M
    We need to resize this because a new application is being promoted, and we have tested it in Pre-PRO
    The thing is that after the new size and before deploying the new app,
    all the 'Old Collection Reasons' are due to 'Artifical: Cleaning up Finished Threads' and the top of the HEAP (4GB) is never reached
    A sample:
    [gcpause][Wed Feb 27 22:29:26 2013][01719] [OC#621] [---] 1498,525 ms (611967,663000-611969,161000) OC
    [gcpause][Wed Feb 27 22:29:26 2013][01719] [OC#621] [con] 0,004 ms (611967,663000-611967,663000) OC:PreGC
    [gcpause][Wed Feb 27 22:29:26 2013][01719] [OC#621] [pau] 1453,742 ms (611967,663000-611969,116000) OC:Main
    [gcpause][Wed Feb 27 22:29:26 2013][01719] [OC#621] [con] 43,411 ms (611969,118000-611969,161000) OC:PostGC
    [memory ][Wed Feb 27 22:29:26 2013][01719] [OC#621] 611967,663-611969,161: OC 2982855KB->1227524KB (4194304KB), 1,499 s, sum of pauses 1453,742 ms, longest pause 1453,742 ms.
    After examinig the correponding JFR we haven't any issue or hotspot in the code that could justify this behaviour, in fact the same that works right with 2,8 GB HEAP
    Googling hasn't given us any answer and the Support mates are requiring us some more information, but they say this is normal (something that I don't agree at all)
    Any suggestion will be welcome ... thanks in advance
    We're running:
    java version "1.5.0_26"
    Java(TM) Platform, Standard Edition for Business (build 1.5.0_26-b03)
    Oracle JRockit(R) (build R28.1.1-14-139783-1.5.0_26-20101206-0241-linux-x86_64, compiled mode)
    and:
    HT is: not supported by the CPU, not enabled by the OS, not enabled in JRockit.
    CPU: Intel Core 2 SSE SSE2 SSE3 SSSE3 SSE4.1 Core Intel64
    Vendor: GenuineIntel
    Family: Core 2
    Model: Core 2
    Name: Intel(R) Xeon(R) CPU X7460 @ 2.66GHz
    Sockets: 4
    Cores: 24
    HWThreads: 24
    Supports: On-Chip FPU
    Supports: Virtual Mode Extensions
    Supports: Debugging Extensions
    Supports: Page Size Extensions
    Supports: Time Stamp Counter
    Supports: Model Specific Registers
    Supports: Physical Address Extension
    Supports: Machine Check Exceptions
    Supports: CMPXCHG8B Instruction
    Supports: On-Chip APIC
    Supports: Fast System Call
    Supports: Memory Type Range Registers
    Supports: Page Global Enable
    Supports: Machine Check Architecture
    Supports: Conditional Mov Instruction
    Supports: Page Attribute Table
    Supports: 36-bit Page Size Extension
    Supports: the CLFLUSH Instruction
    Supports: the Debug Trace Store feature
    Supports: ACPI registers in MSR space
    Supports: Intel Architecture MMX Technology
    Supports: Fast Float Point Save and Restore
    Supports: Streaming SIMD extensions
    Supports: Streaming SIMD extensions 2
    Supports: Self-Snoop
    Supports: Hyper Threading
    Supports: Thermal Monitor
    Supports: Streaming SIMD Extensions 3
    Supports: 64-bit DS Area
    Supports: MONITOR/MWAIT instructions
    Supports: Virtual Machine Extensions
    Supports: Enhanced Intel SpeedStep technology
    Supports: Thermal Monitor 2
    Supports: Supplemental Streaming SIMD Extensions 3
    Supports: CMPXCHG16B
    Supports: xTPR Update Control
    Supports: Perfmon and Debug Capability
    Supports: Direct Cache Access
    Supports: Streaming SIMD extensions 4.1
    Supports: LAHF/SAHF instruction support
    Supports: SYSCALL/SYSRET
    Supports: Intel 64 Architecture
    [memory ][Wed Feb 20 20:29:57 2013][01719] Running with 32 bit heap and compressed references supporting 32GB heap.
    [memory ][Wed Feb 20 20:29:57 2013][01719] GC mode: Garbage collection optimized for throughput, strategy: Generational Parallel Mark & Sweep.

    "as I understand GcTrigger only applis for concurrent GC, and in fact we are having genpar (parallel)"
    Yep, "The garbage collector ignores the -XXgcTrigger value when it runs both parallel mark and parallel sweep, for example if you specify -Xgc:singlepar or -Xgc:genpar on the command line."
    Why not set a dynamic collection scheme (http://docs.oracle.com/cd/E15289_01/doc.40/e15062/optionx.htm#i1011879):
    throughput - The garbage collector is optimized for application throughput. This means that the garbage collector works as effectively as possible, giving as much CPU resources to the Java threads as possible. This might, however, cause nondeterministic pauses when the garbage collector stops all Java threads for garbage collection.The throughput priority should be used when non-deterministic pauses do not impact the application's behavior.
    pausetime - The garbage collector is optimized for short pauses. This means that the garbage collection works concurrently with the Java application when necessary, in order to avoid pausing the Java threads. This inflicts a slight performance overhead to the application, as the concurrent garbage collector demands more system resources (CPU time and memory) than the parallel garbage collector that is used for optimal throughput. The target pause time is by default 500 msec. To change the default pause target, see -XpauseTarget.
    On an application server going for throughput gives good results, when you want to reduce the stop-the-world times it might be beneficial to use pausetime with an appropriate pausetarget.
    "...we need to increase HEAP size to cover application expectations"
    It should be fine to increase the heap size (we are running JRockit with 16G in certain environments, with the pausetime as the dynamic garbage collection setting), i.e.,
    -Xms16g -Xmx16g -Xns1024m -Xgc:pausetime -XpauseTarget:200ms (in this case the application contains a lot of session data which is placed in the old generation hence
    the choice for 16G) as long as you keep the live data below 2/3 of the heap, the collection time introduced should be near the 200millis.
    http://middlewaremagic.com/weblogic/?page_id=7132 (contains a bunch of posts on JVM tuning)

  • How do you dispose a thread-handled modal dialog not thru some actions?

    The code almost looks like this:
    /* Thread that disposes the dialog when the time in seconds is "9" */
    class AboutThread extends Thread {
    private volatile Thread about;
    AboutDialog ad;
    AboutThread(AboutDialog ad) {
    this.ad = ad;
    public void stopped() {
    about = null;
    ad.dispose();
    ad = null;
    System.gc();
    public synchronized void run() {
    Thread thisThread = Thread.currentThread();
    about = thisThread;
    System.out.println("About thread is running!");
    ad.start();
    while (about == thisThread) {
    try {
    Thread.sleep(1000);
    } catch (InterruptedException ex) {
         System.err.println("Thread.sleep error: " + ex);
    String s = new String(getCurrentDateTime("s"));
    if (s.equals("9")) {
    ad.setVisible(false);
    ad.setModal(false);
    ad.setVisible(true);
    System.out.println(9);
    this.stop();
    /* Shows a dialog describing the User Log application */
    public class AboutDialog extends Dialog implements ActionListener {
    public AboutDialog(Frame parent, String title) {
         super(parent, title, false);
         Panel labelPanel = new Panel();
         labelPanel.setLayout(new BorderLayout());
         labelPanel.setBackground(Color.gray);
    JLabel jlab = new JLabel("User Log 1.0");
    jlab.setHorizontalAlignment(SwingConstants.CENTER);
    jlab.setFont(new Font("Monospaced", Font.BOLD, 28));
    JLabel jlab1 = new JLabel("Copyright(c) 2001 Soft Wares. All Rights Reserved.");
    jlab1.setHorizontalAlignment(SwingConstants.CENTER);
    labelPanel.add(jlab, "Center");
         labelPanel.add(jlab1, "South");
         add(labelPanel, "Center");
         Panel buttonPanel = new Panel();
    buttonPanel.setBackground(Color.gray);
         Button okButton = new Button("OK");
         okButton.addActionListener(this);
         buttonPanel.add(okButton);
         add(buttonPanel, "South");
         setSize(400, 130);
         setLocation(parent.getLocationOnScreen().x + 200,
              parent.getLocationOnScreen().y + 200);
    public void start() {
    show();
    public void actionPerformed(ActionEvent e) {
         setVisible(false);
         dispose();
    at.stopped();
    }

    ooops! i'm sorry. in the AboutDialog Class, it should be "super(parent, title, true)" for it to be modal.
    anyway, it seemed that posting the partial code above of the whole app is not so understandable.
    what i like to address here is that: how do i dispose or get rid of the thread-dispatched modal dialog by not making mouse clicks or any other user intervention? i wanted it to be disposed by the same thread, which dispatched it, when a certain variable value (global or local) is met. is this possible?

  • Please clean up this thread

    Justin, please clean out the flames in this thread:
    http://forums.oracle.com/forums/thread.jspa?messageID=2395239#2395239
    Like I said in my message at the bottom of the thread, anyone who posts insults like these should be banned from posting for a period of time. I would suggest a week.
    And unfortunately, the most offensive person posting in the thread posted incorrect information anyway.
    Here are some quotes from the thread:
    "I don't know why the information I already provided wore out in your brain so quickly.
    One would wonder why you would provide it, if it enters one ear and departs from the other ear in a split second."
    I would recommend you look in the mirror, notice you look ugly, and find another playground.
    And checking his profile, I see he is spewing his flames and insults even today: http://forums.oracle.com/forums/message.jspa?messageID=2427899#2427551

    I see the threads I referred to have been completely deleted.
    Unfortunately, I had posted a message at the end of the one concerning Forms where I corrected the erroneous information. So now both the original poster asking the questions, as well as the offending responder both will not know that the information was wrong.
    I was hoping only the offensive posts and the replies to them could have been removed.

  • How does WebLogic clean up stuck threads?

    Hi,
    Using WebLogic 9.2.2 on Linux OS. In our logs, we are finding some stuck threads and it seems to be due to something WebLogic is doing. While we don't understand the cause (maybe the stack trace helps), does WebLogic do anything to remove stuck threads from its pool, or is there anything we can do to configure it to?
    <Jul 21, 2009 2:50:21 PM UTC> <Error> <WebLogicServer> <BEA-000337> <[STUCK] ExecuteThread: '2' for queue: 'weblogic.kernel.Default (self-tuning)' has been busy for "605" seconds working on the request "Http Request: /RoutingEngine/pcFlow.do", which is more than the configured time (StuckThreadMaxTime) of "600" seconds. Stack trace:
    Thread-69 "[STUCK] ExecuteThread: '2' for queue: 'weblogic.kernel.Default (self-tuning)'" <alive, in native, suspended, priority=1, DAEMON> {
    jrockit.net.SocketNativeIO.readBytesPinned(Unknown Source)
    jrockit.net.SocketNativeIO.socketRead(Unknown Source)
    java.net.SocketInputStream.socketRead0(SocketInputStream.java:???)
    java.net.SocketInputStream.read(SocketInputStream.java:107)
    java.io.BufferedInputStream.fill(BufferedInputStream.java:189)
    java.io.BufferedInputStream.read(BufferedInputStream.java:234)
    ^-- Holding lock: java.io.BufferedInputStream@3537712[thin lock]
    weblogic.net.http.MessageHeader.isHTTP(MessageHeader.java:214)
    weblogic.net.http.MessageHeader.parseHeader(MessageHeader.java:141)
    weblogic.net.http.HttpClient.parseHTTP(HttpClient.java:473)
    ^-- Holding lock: java.io.BufferedInputStream@3537712[thin lock]
    weblogic.net.http.HttpURLConnection.getInputStream(HttpURLConnection.java:332)
    ^-- Holding lock: java.io.BufferedInputStream@3537712[thin lock]
    weblogic.net.http.SOAPHttpURLConnection.getInputStream(SOAPHttpURLConnection.java:36)
    weblogic.wsee.util.dom.DOMParser.getWebLogicDocumentImpl(DOMParser.java:92)
    weblogic.wsee.util.dom.DOMParser.getDocument(DOMParser.java:56)
    weblogic.wsee.wsdl.WsdlReader.getDocument(WsdlReader.java:311)
    weblogic.wsee.wsdl.WsdlReader.getDocument(WsdlReader.java:305)
    weblogic.wsee.wsdl.WsdlSchema.parse(WsdlSchema.java:120)
    weblogic.wsee.wsdl.WsdlSchemaImport.parse(WsdlSchemaImport.java:55)
    weblogic.wsee.wsdl.WsdlSchema.parse(WsdlSchema.java:82)
    weblogic.wsee.wsdl.WsdlSchema.parse(WsdlSchema.java:62)
    weblogic.wsee.wsdl.WsdlTypes.parse(WsdlTypes.java:145)
    weblogic.wsee.wsdl.WsdlDefinitions.parseChild(WsdlDefinitions.java:452)
    weblogic.wsee.wsdl.WsdlExtensible.parse(WsdlExtensible.java:84)
    weblogic.wsee.wsdl.WsdlDefinitions.parse(WsdlDefinitions.java:378)
    weblogic.wsee.wsdl.WsdlDefinitions.parse(WsdlDefinitions.java:358)
    weblogic.wsee.wsdl.WsdlFactory.parse(WsdlFactory.java:50)
    weblogic.wsee.jaxrpc.ServiceImpl.loadWsdlDefinition(ServiceImpl.java:437)
    weblogic.wsee.jaxrpc.ServiceImpl.<init>(ServiceImpl.java:95)
    com.myco.regui.provisioning.client.ProvisioningAccountService_Impl.<init>(ProvisioningAccountService_Impl.java:21)
    com.myco.regui.provisioning.client.ProvisioningAccountService_Impl.<init>(ProvisioningAccountService_Impl.java:17)
    com.myco.regui.struts.accounts.AccountsForm.contactWPS(AccountsForm.java:208)
    com.myco.regui.struts.accounts.AccountsForm.validateAccountid(AccountsForm.java:161)
    com.myco.regui.struts.accounts.AccountsForm.validatePCAccountId(AccountsForm.java:144)
    com.myco.regui.struts.accounts.AccountsForm._validatePCFields(AccountsForm.java:112)
    com.myco.regui.struts.accounts.AccountsForm.validate(AccountsForm.java:83)
    org.apache.struts.chain.commands.servlet.ValidateActionForm.validate(ValidateActionForm.java:57)
    org.apache.struts.chain.commands.AbstractValidateActionForm.execute(AbstractValidateActionForm.java:94)
    org.apache.struts.chain.commands.ActionCommandBase.execute(ActionCommandBase.java:48)
    org.apache.commons.chain.impl.ChainBase.execute(ChainBase.java:176)
    org.apache.commons.chain.generic.LookupCommand.execute(LookupCommand.java:303)
    org.apache.commons.chain.impl.ChainBase.execute(ChainBase.java:176)
    org.apache.struts.chain.ComposableRequestProcessor.process(ComposableRequestProcessor.java:272)
    org.apache.struts.action.ActionServlet.process(ActionServlet.java:1903)
    org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:462)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:736)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:851)
    weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:224)
    weblogic.servlet.internal.StubSecurityHelper.invokeServlet(StubSecurityHelper.java:108)
    weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:198)
    weblogic.servlet.internal.TailFilter.doFilter(TailFilter.java:26)
    weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:41)
    com.myco.regui.servlets.filters.TransactionFilter.doFilter(TransactionFilter.java:23)
    .......

    You can configure these actions to occur when not all threads are stuck, but the number of stuck threads have exceeded a configured threshold:
    * Shut down the Work Manager if it has stuck threads. A Work Manager that is shut down will refuse new work and reject existing work in
    the queue by sending a rejection message. In a cluster, clustered clients will fail over to another cluster member.
    * Shut down the application if there are stuck threads in the application. The application is shutdown by bringing it into admin mode. All
    Work Managers belonging to the application are shut down, and behave as described above.
    * Mark the server instance as failed and shut it down it down if there are stuck threads in the server. In a cluster, clustered clients that
    are connected or attempting to connect will fail over to another cluster member.
    Link : [http://e-docs.bea.com/wls/docs103/config_wls/overload.html]

  • What is the proper method for cleaning up EventWaitHandle?

    Hi all,
    I'm working on inter-process communication between applications running on the same machine. More specifically I have a primary application that is connected to multiple industrial machines collecting data from each.
    I want to create secondary applications that consume this data. I intend on using MemoryMappedFile to share the information. I've tested the MMF part and it works fine.
    I'm at the point where I want to notify the client applications when new data is available by using an EventWaitHandle. I create the handle as follows.
    handle = new EventWaitHandle(false, EventResetMode.AutoReset, ClientName);
    In the client application I use WaitOne inside a thread for the event notification. This too works well.
    private void MonitorForSignal()
    running = true;
    bool signaled;
    while (running)
    signaled = handle.WaitOne();
    if (signaled)
    if (!handle.SafeWaitHandle.IsClosed)
    //Do something
    I create the thread as follows:
    monitor = new Thread(MonitorForSignal);
    monitor.IsBackground = true;
    running = true;
    monitor.Start();
    My concern is that I may be creating an orphaned thread or a memory leak when I close the client application. So I implemented IDisposable in my client class and do the following.
    protected virtual void Dispose(bool disposing)
    if (disposing)
    // free managed resources
    // free native resources here if there are any
    running = false;
    handle.Close();
    handle.Dispose();
    monitor.Abort();
    I believe this does indeed free the resources, but I've read that Thread.Abort is "bad". Before I implemented IDisposable I did some testing in a couple of WinForm applications, one acting as the host and one as the client. I noticed that I could
    close the client and subsequently Set the EventWaitHandle in the host application and this line of code in the client would fire in the debugger.
    signaled = handle.WaitOne();
    This made me worry that I wasn't properly cleaning up my thread objects.
    Below is the entire client for reference. What I'm really asking is how do I properly clean up the MonitorForSignal thread and the EventWaitHandle in the client?
    public class ClientA : IDisposable
    bool running;
    string clientName;
    EventWaitHandle handle;
    Thread monitor;
    private void MonitorForSignal()
    running = true;
    bool signaled;
    while (running)
    signaled = handle.WaitOne();
    if (signaled)
    if (!handle.SafeWaitHandle.IsClosed)
    //Do something
    private void ProcessData()
    //Do Something
    public ClientA(string ClientName)
    if (ClientName == null || ClientName == string.Empty)
    throw new ArgumentException("Cannot be null or empty.", "ClientName");
    clientName = ClientName;
    handle = new EventWaitHandle(false, EventResetMode.AutoReset, ClientName);
    monitor = new Thread(MonitorForSignal);
    monitor.IsBackground = true;
    running = true;
    monitor.Start();
    #region IDispose
    ~ClientA()
    Dispose(false);
    public void Dispose()
    Dispose(true);
    GC.SuppressFinalize(this);
    protected virtual void Dispose(bool disposing)
    if (disposing)
    // free managed resources
    // free native resources here if there are any
    running = false;
    handle.Close();
    handle.Dispose();
    monitor.Abort();
    #endregion
    Regards,

    Hi Michael,
    Does this code cause the thread to spin?
    while (!handle.WaitOne())
    //TODO: Do work
    Thread.Sleep(1000);
    I was hoping not to spin thus the EventWaitHandle. As for the named handle, I am building multiple applications that need to have inter-process communication, all running on the same machine.
    I think I can update my class to use your recommendation for the dispose method, specifically using handle.Set
    However, I would update the MonitorForSignal as follows:
    bool _closing = false;
    private void MonitorForSignal()
    running = true;
    bool signaled;
    while (running)
    signaled = handle.WaitOne();
    if (signaled && !_closing )
    if (!handle.SafeWaitHandle.IsClosed)
    if (NewData != null)
    NewData();
    And the dispose as follows:
    protected virtual void Dispose(bool disposing)
    if (disposing && handle!=null)
    running = false;
    _closing = true;
    handle.Set();
    if (!monitor.Join(5000))
    monitor.Abort();
    monitor = null;
    handle.Dispose();
    handle = null;
    // free managed resources
    // free native resources here if there are any
    This allows me to skip over the "Do Work" part which should only be done when Signaled from another application. Your suggestion to use handle.Set() in the dispose method coupled with adding the bool _closing allows me to get past the EventWaitHandle
    and also skip the work when closing.
    Also by setting "running" to false in the dispose, the thread will naturally end after the wait handle has been set.
    Thanks for suggesting the Thread.Join, that does seem allot more graceful. When I tested these changes it was blazing fast. In the previous code when I called monitor.Abort the application would hang for about a second. 
    Do you think the changes capture the intent of your suggestions?
    Regards,

  • Properly closing socket and killing thread in cmd window

    Hey all,
    I'm creating my socket connection in a program that i am running in a cmd window. For what i need in my prog, i have a loop that tries to connect every 5 seconds, and even after that, I need to continue looping to check and try to connect.
    The only way i can end the program is to cntrl-c or X out of the program. What i need to know is there a way to properly clean up the thread and close the socket w/o any memory leak issues?
    Thanks

    What i need to know is there a
    way to properly clean up the thread and close the
    socket w/o any memory leak issues?All modern popular use OSes clean sockets, threads and memory (normal) when the application exits for any reason at all.

  • 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);
    }

  • "Safe" delete of Thread class from a Vector

    I need to be able to delete a thread class object from a vector.
    1) Is it safe to do so immedately after calling xyz.stop() ?
    2) If so, does Java clean all the thread stuff up automatically ?
    3) If not, is there something else I should do to clean up?

    The stop method of class Thread is deprecated, however it's still possible to stop this thread. A thread's memory should become available for garbage collection the moment it is no longer executing, and it is no longer being reffered to.
    To stop your thread, you need to set a boolean flag that is available to it to false:
    Thread myThread = new Thread()
         public boolean stopRunning = false;
         public boolean threadComplete = false;
         public void run()
              while(!stopRunning)
                   doSomething();
              threadComplete = true;
    }If you are doing something involving blocking I/O inside your thread, you're going to need to interrupt the thread after setting this public flag to true in order to get it to stop executing.
    Then you can simply remove it's refference from that Vector, and it will become elligable for Garbage collection the moment it becomes inactive.
    -Jason Thomas.

  • Replies from Mac Outlook 2011 prevent message from being cleaned up by Clean Up feature on Outlook 2013 on Windows

    I'm noticing a trend that if someone using Outlook 2011 on OSX, if they reply to an email, then someone replies after that, if you try to Clean Up the thread or the folder, Outlook 2013 on a PC will not delete the reply from the Mac user, as it appears to
    have an attachment.  I think it may be tied to having screenshots in an email, or if they have an image in their signature.
    Has anyone else experienced this, or know of a way to fix it?  Or would Microsoft have to change something in Outlook 2011 for OSX?

    Hi,
    Since I don't have an Outlook for Mac, I'm not able to do the test for you right now.
    If you have Outlook for Mac, you can test it yourself:
    In Outlook 2013, tick one checkbox each time under Conversation Clean Up, then send an email from Outlook for Mac, try to clean up in Outlook 2013, check the result. This may help determine which option that caused the issue.
    Regards,
    Melon Chen
    Forum Support
    Come back and mark the replies as answers if they help and unmark them if they provide no help.
    If you have any feedback on our support, please click
    here

  • Automatic thread creation?

    Hi,
    While linking a 3rd party library I noticed that my single threaded program was being recognized as multi-threaded by workshop & also the executable had 4 threads running. After some investigation, I realized that this was due to the library having a dependency on pthreads. I was able to duplicate this by writing a c program and linking with either pthreads or threads.
    foo.c:
    main ()
    while (1)
    Compiling & linking this with :
    cc foo.c -lthread
    & executing this :
    a.out &
    Now the "ps -L" command displays 3 threads with only one of the threads running. My question is whether this is normal or can I set any compiler flags/apply any patches to change this behaviour?
    My development environment is Solaris 8 with Forte 6.2
    Thanks,

    The four threads your seeing are :
    The primary thread (The one you expect)
    A ASLWP thread to handle signals
    A reaper thread to clean up detached threads
    An lwp that deals with the kernel
    This is due the the MxN thread model type that Solaris 8 and
    lower has.
    If you use Solaris 9 or use the threads library at /usr/lwp/libthread
    instead of /usr/lib/libthread on Solaris 8, (set your
    LD_LIBRARY_PATH), you will just see the primary thread.
    This is because a one-to-one threading model is used here.
    Solaris 8 actually shipped both thread models.

  • Memory-capped sub-process (thread, separate JVM...?)

    I'm working on a project that has a thread that may take up a lot of memory, possibly enough to throw an OutOfMemoryError (or occasionally a StackOverflowException). Is there any way to cap the amount of memory available to this thread to, say 90% of the JVM's memory, and if the thread goes over that, gracefully clean up the thread and allow the user to continue using the application normally, albeit without that memory-intensive feature (i'd probably manually run a GC cycle after it).
    Thanks,
    Robert

    No, this needs to be redesigned such that it won't feel the need to be such a resource hog in the first place. And if you're getting StackOverflowExceptions, you know that's a different animal than an OutOfMemoryError, right? That would mean very deep call stacks (such as a very deep recursive call chain) and/or lots and lots of local variables in humongous methods which probably need to be refactored.

  • JDialog, dispose, and JVM exit

    Why is it that running this code: import javax.swing.JDialog;
    public class Temp {
         public static void main(String args[]) {
              JDialog dialog = new JDialog();
              dialog.setVisible(true);
              dialog.dispose();
              dialog = null;
    }does not cause the JVM to terminate, but running this code: import javax.swing.JDialog;
    public class Temp {
         public static void main(String args[]) {
              JDialog dialog = new JDialog();
    //          dialog.setVisible(true);
              dialog.dispose();
              dialog = null;
    }does? What I want to happen is to cleanly dispose of the JDialog without terminating the JVM --- thus, System.exit(0) is not a viable solution here (unlike the similar JFrame problem).

    Use the setDefaultCloseOpration() thus:
    <code>
    import javax.swing.JDialog;
    public class Temp {
         public static void main(String args[]) {
              JDialog dialog = new JDialog();
         dialog.setVisible(true);
              dialog.dispose();
    dialog.setDefaultCloseOperation(JDialog.EXIT_ON_CLOSE);
    </code>

  • Java Panic, Unable to suspend threads, 1024 (more?)times

    I got this error message, after adding up more and more functionality.
    Someone already familiar with the reasons for such a message?

    I have managed to correct my problem
    The problem existed when I was disposing of a frame and then immediately afterwards running the garbage collector. I have modified my code in the following way whicfh seems ot have corrected the problem.
    Old Code:
    frame.dispose();
    System.gc();
    New Code:
    Frame.Dispose();
    try {
    Thread.currentThread().sleep(100);
    catch(Exception e) { }
    System.gc();
    This has corrected the panic I was receiving.
    Check for specific instances where you are running the garbage collector and change as done above.

  • INCompressor thread lagging

    I have a tool which I run when I end up with a large cleaner backlog. It's based on some sample code I fished out of the forum, and it basically just opens the environment, optionally deletes a couple of expendable databases, manually runs the cleaner in several threads until the backlog is gone, and closes the environment. (Both je.env.runCleaner and je.env.runCheckpointer are set to false.)
    I've noticed that in some cases the INCompressor thread keeps running after the final checkpoint has finished, leading to a very large recovery time when the environment is next opened (because a lot ends up being written to the log after the last checkpoint). I presume this is due to the large number of cleaner threads.
    (I see that early in the environment close code, the daemon threads are notified to exit, but the INCompressor code doesn't check this flag until after it has finished a set of work items, and I'm guessing it's working through a very long list.)
    As a test, I set je.env.runINCompressor to false for a run of my tool, and in this case the environment closes quickly and also subsequently opens quickly. But I don't know what the consequences are, of not running the INCompressor thread at all during this operation. Is this safe to do? Does it cause bloat in the log files (because it's skipping some sort of cleanup)?
    I didn't see any way to manually wait for the INCompressor thread to terminate before issuing a final checkpoint, so disabling the INCompressor thread was the only workaround I could think of.
    (This is under JE 4.1.17.)

    (I see that early in the environment close code, the daemon threads are notified to exit, but the INCompressor code doesn't check this flag until after it has finished a set of work items, and I'm guessing it's working through a very long list.)Correct. We may want to improve this by exiting the compression loop sooner when the environment is being shut down, but that may have negative effects as well. I don't think we've done an analysis of the trade-offs. Thanks for pointing it out.
    As a test, I set je.env.runINCompressor to false for a run of my tool, and in this case the environment closes quickly and also subsequently opens quickly. But I don't know what the consequences are, of not running the INCompressor thread at all during this operation. Is this safe to do? Does it cause bloat in the log files (because it's skipping some sort of cleanup)?There is a drawback to disabling the compressor thread, which is that deleted branches of the Btree (if you've deleted large ranges of records) or individual record slots (if you haven't) will not be removed from the Btree before the final checkpoint. Although these will be removed eventually, after opening the environment later, it is more efficient for them to be removed before the checkpoint, since there will be less total writing of the log.
    I didn't see any way to manually wait for the INCompressor thread to terminate before issuing a final checkpoint, so disabling the INCompressor thread was the only workaround I could think of.There is another way to force the compressor to finish its work: After doing your log cleaning, call Environment.compress(). This method is synchronized, so it will block if compression is running in the background thread, and then try compressing again. In any case, when it returns, compression will be complete. Then close the environment.
    Please let us know if this helps.
    One thing I'm confused about is that you said delete a couple databases and then run the log cleaner. Bu if you're calling Environment.removeDatabase or truncateDatabase, compression will not be necessary, so I'm not sure why the compressor is doing so much work. Are you deleting individual records? If so, that explains it.
    --mark                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

Maybe you are looking for

  • Generate XML File from table

    How to generate XML file from a table without using UTL_FILE that too in local machine...

  • IBook G4- Wireless Connection Faulty

    It connects, then it disconnects, then reconnects, etc. etc. I wanted to buy the F5D7050 Belkin USB Wireless but it says it is only Windows compatable. I really want to end this whole faulty wireless thing. It's driving me insane. I almost threw my l

  • Authorization objects for  transaction, one to view, and one to maintain

    Hi all, My requrement is to create two authorization objects for  transaction, one to view, and one to maintain. I know how to create objetcs vai sm21, but i donot know how to crate objects with activity codes. Please suggest how to create object whe

  • Role problems using RIMLoginModule

    Hi all, we are currently trying to execute an web application using the RIMLoginModule with a blackberry. For this reason, we have to configure the module on: http://servername:port/webdynpro/dispatcher/sap.com/mba~com.sap.mbs.mso.main/MSOMain Unfort

  • Reader 11.0.09 freezing upon opening

    Since updating to Adobe Reader version 11.0.09, user's are seeing freezing (not responding) when trying to scroll up/down or use the menus. This happens for about 30 seconds before it begins to work normally. It seems to be related to this newer vers