Solving a Matlab hang problem

Closing a modal dialog may hang Matlab

Closing a modal dialog may hang Matlab

Every now and then I stumble on a case where Matlab hangs, becomes totally unresponsive and requires me to kill the Matlab process externally (via the task manager). The undocumented solution is frustratingly simple (see below), and yet I keep forgetting it.

The last time this happened was only two days ago, and by pure coincidence a reader’s comment yesterday happened on the same page where I explained the problem and solution. So I am taking this opportunity to explain the problem and the workaround, before my senility takes over and I forget again… :-)

The symptom – Matlab hangs

The symptom is easily detectable: you’re happily working on your favorite Matlab GUI application, when suddenly some modal dialog window appears – perhaps a msgbox, a questdlg or an inputdlg. After clicking the <OK> button, Matlab seems to freeze, and any attempt to close the window or to stop the GUI fails. Forget about Ctrl-C – it simply hangs.

The only workaround is to open the operating system’s task manager and kill the Matlab process.

There are several odd things here: Firstly, the task manager shows that the Matlab process is not consuming any CPU. Secondly, the hang does not appear consistently – sometimes it does, other times not, making debugging extremely difficult. Moreover, when we debug the code, stepping through the source-code lines one at a time, everything seems to behave perfectly normal; it is only when running the program in continuous mode that the hang appears.

The solution – adding drawnow

The underlying reason for the hang appears to be that when we close the modal dialog window, it is sometimes not yet fully destroyed when we proceed with our program. It is my belief that this creates race-conditions which in some cases cause a deadlock between Matlab’s Main Thread and Java’s Event Dispatch Thread (EDT). Matlab-EDT synchronization problems are often time-dependent, which explains why the hang sometimes occurs and sometimes not.

While debugging EDT synchronization problems is notoriously difficult, the solution is often extremely simple — Just add a combination of drawnow and a short pause:

uiwait(msgbox(...));
drawnow; pause(0.05);  % this innocent line prevents the Matlab hang 
answer = questdlg(...);
drawnow; pause(0.05);  % this innocent line prevents the Matlab hangswitch answer
   ...

Adding drawnow and pause forces Matlab to flush EDT’s event queue, thereby ensuring synchronization before proceeding with the Matlab code. This is actually quite important when integrating Java GUI components in Matlab figures (especially before R2008b’s javaObjectEDT became available).

In the particular case of the Matlab dialog hang, drawnow is probably sufficient and pause is unnecessary. As noted by Bill York (MathWorks’ dev team leader who is responsible for such stuff) here, drawnow is similar but not exactly the same as pause. I often use both of them, since I discovered via trial-and-error that in the general case of EDT-related timing issues, different situations respond better to either of them, and I never remember which one to use to ensure proper rendering. So the drawnow/pause line appears very often in my code, quite possibly even in places where they are not strictly needed.

The actual needed value of the pause may vary, depending on GUI complexity and CPU power/load, but 0.05 seems to be large enough for most cases, while being small enough to be virtually unnoticeable by the user. In rare cases I needed to go as high as 0.1, but then again in some cases it is not needed at all.

Categories: GUI, Low risk of breaking in future versions, Undocumented feature

Tags: , , ,

Bookmark and SharePrint Print

37 Responses to Solving a Matlab hang problem

  1. Aurélien says:

    I am glad to see that I am not the only one to have this issue. I get this issue on Windows Xp Win32 since R2011b . I exactly use the same workaround by adding a pause(0.1) after each dialog box , otherwise MATLAB freezes or requires some time to be able to close the dialog box. It often occurs when I have a lot of code just after the dialog box . It is just like if MATLAB was already interpreting the rest of the code before the user clicks on the dialog box…. As I was never able to reproduce easily this issue with a simple code , I never submitted technical support request.

  2. andrew says:

    I’ve gotten a very similar problem on numerous occasions, though I’ve never been able to find mention of it online. When I use alt+tab (Windows 7, R2009a) to switch between the command window and an auxiliary Matlab screen (help, find files, …), it occasionally hangs. Button mashing sometimes fixed it, though I could never find out what the exact trigger to resume was. I later realized killing the specific process through task manager was a better solution.

    Thanks for the great blog, Yair. I’m surprised you don’t have a cushy job at MathWorks by now, unless, of course, you don’t want one!

    • Chin says:

      I currently face this similar issue too.
      I am using Windows 7 platform, and I have tried using both Matlab R2010a and R2011b versions, this same problem still happened every time I did a alt-tab on the Help windows to switch between windows.

      Other than killing the Matlab process via Task Manager, have you found any solution to solve this?

      Thank you!

  3. Matt Whitaker says:

    Yes, this can be very irritating. Wasted over an hour on this the other day before sticking in a drawnow. What was “interesting” was that the very same code that would hang in R2012b ran flawlessly in R2011a. We will just have to program defensively and put them in all these situations I guess..

  4. Andrew Ness says:

    I was just trying to figure out this same issue myself – perfect timing on your post! Thank you.

  5. Yes. I had similar issues too!
    I blogged about it.
    I would tend to think this is a serious Matlab bug as the behavior is not expected and can lead to very long and annoying debugging.
    I have the feeling Matlab is most of the time unstable due to its interaction with Java. What do you think?

    In general, every time I get a Java error like this in Matlab, I feel a little lost. These are the most difficult to debug. So this post was very helpful.

    • @Jerome – I wouldn’t go as far as saying that the Matlab-Java interface makes Matlab unstable. I believe that if we stick to some well-defined rules (that I have outlined in section 1.5 of my book), then we should be ok and our application would be quite stable.

      I would of course hope that making a stable high-quality GUI would involve less hand-crafting by Matlab users than currently required, but this is still a long way from saying that it is unstable or unuseful.

      I do agree that debugging such issues can often be frustratingly difficult. I can only console you that it gets easier with experience, as the problems tend to be similar to each other, and the solutions similar as well.

    • TheBlackCat says:

      @Yair: I would have to disagree with you. You have to sprinkle your code with undocumented workarounds just to prevent it from hard freezing under ordinary usage, with no debugging information provided to help you figure out what went wrong. If that is not unstable, then what would be?

  6. sebbo says:

    Hi Yair,

    I’m having a similar (I think…) problem, with pop-ups that are created from uimenus.
    For example I’m having a rather busy gui out of which one uimenu calls a another function, that creates a figure waiting for user input.

    I’m regurlary encountering the issue, that those kind of pop-up windows (also e.g. the “questdlg”-figures) are not drawn properly.
    For instance their background is transparent, some ui-elements don’t appear at all, etc.

    I’ve already distributed pause & drawnow-calls, but these didn’t solve the problem.

    I’d be glad about any idea on how to solve this.

  7. girlfromgraz says:

    Hey,

    I encountered a similar-ish behaviour with a slider that positions a plot object within my gui. Everything worked smooth when positioning by either clicking in the slider’s trough or via numerical values of an additional text box (that always shows the current position values – I guess you get the idea).
    BUT upon moving my plot object via clicking the slider’s arrows, the slider itself kept moving until reaching its min or max value, freezing Matlab on its way.

    I first tried “pause(0.05)” as in your example, but I only got my slider’s behaviour right once I changed to “pause(0.1)”.

    Long story short: thanks for your post, it helped a great deal. (Though I’ve got no idea why the length of the pause should be substantial to your workaround.)

  8. Pingback: Using Java 7 in Matlab R2013a and earlier | Undocumented Matlab

  9. Jerome Lecoq says:

    Hi Yair,

    I am having a very annoying related issue when using uitree. I have quite a complex program that fill up a tree interactively and 99% of the time, this goes fine but in some rare cases, the tree will not be filled or some calls to java tree functions do not finish. I did place a few drawnow and pause and I think it did improve but the issue is still coming back from time to time. Sometime the tree will take 10s to be refreshed (in most cases, it is rather in the ms scale). I wondered if you had similar issues?

    • @Jerome – maybe you’re seeing EDT issues. Read the EDT article for some suggestions.

    • I suppose you are right, although I really followed all your examples on using uitree/JTree in either your book/website.

      I get this sort of error on the terminal :

      Exception in thread “AWT-EventQueue-0” java.lang.NullPointerException
      at com.mathworks.mwswing.MJTree.processMouseEventImpl(MJTree.java:414)
      at com.mathworks.mwswing.MJTree.processMouseEvent(MJTree.java:397)
      at java.awt.Component.processEvent(Unknown Source)
      at java.awt.Container.processEvent(Unknown Source)
      at java.awt.Component.dispatchEventImpl(Unknown Source)
      at java.awt.Container.dispatchEventImpl(Unknown Source)
      at java.awt.Component.dispatchEvent(Unknown Source)
      at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
      at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
      at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
      at java.awt.Container.dispatchEventImpl(Unknown Source)
      at java.awt.Component.dispatchEvent(Unknown Source)
      at java.awt.EventQueue.dispatchEvent(Unknown Source)
      at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
      at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
      at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
      at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
      at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
      at java.awt.EventDispatchThread.run(Unknown Source)

    • As you can see this is due to a bug in Matlab’s MJTree class, that apparently happens in some timing edge case. This is an internal class that you cannot modify.

    • Thanss a lot.
      I think it happens way more often when I reach quite large number of elements in the tree (like several thousands).

      Would you recommend just using pure Java and not use Matlab internal implementation?

    • @Jerome – it’s a tradeoff: uitree is much faster to program, but its maintenance is harder and its functionality is more limited. When you work with pure Java objects (and the javacomponent function that places them in a Matlab GUI), you have far more flexibility, but this requires knowing Java and more development time. The decision is ultimately yours and may depend on the specific situation and requirements.

      It’s similar to the question of whether to use GUIDE or programmatic hand-tailored GUIs. Both of them have their place, it just depends on the specific circumstances.

    • Ok. I will look into that.
      Obviously I have a serious stability issue here. And I need this part of my interface to be reliable so I might seriously look in using pure Java Object. This was my next frontier in Matlab.

  10. Greg says:

    I’ve just had a curious experience with this bug. I’ve been working on a complex GUI with lots of popup dialog boxes in MATLAB R2013b on a Linux machine. Didn’t experience any problems at all with this bug. As soon as I gave the program to a colleague running R2012b on a Windows machine, however, this bug popped up and caused all kinds of crazy MATLAB crashes.

    After a little bit of monkeying around with my different installs on different machines, I could not reproduce the bug in R2013b in Windows or in R2012b in Linux. So, my hunch is that the issue is confined to the Windows environment and may have been fixed in R2013b.

    This is handy, but for someone like me that runs a recent release but with colleagues running older versions, it actually makes it more important to remember to place these little “drawnow; pause(0.05);” lines in your GUI code.

    Thanks for providing the easy fix!

  11. Jack Rayman says:

    Hi.

    I designed a GUI that use parallel computing for accelerating neural network and support vector machines. When I use parallel computing when my program is processing background color of my GUI turn to black (other parts like buttons,text boxes and edit boxes looks normal and updating values correctly). I some cases when I minimized page a little after starting and maximize it again this problem will happen.
    Besides this in both using parallel and not using parallel computing I cant move window that is working correct. It suddenly freezes.

    Thanks,

  12. Bogi Magnussen says:

    I had this issue when showing figures in Matlab, it would hang for 5-10 seconds every time i display a new figure. Thanks for your recommendations, they worked for me as well. The “drawnow” command had no effect in my case, so I only needed the pause() function for the problem to go away.

    Thanks again :)

  13. Eric says:

    Hi Yair,

    I’m having a MATLAB hang issue when I call UISAVE, and the solution above has not solved the issue. I have a fairly complex GUI made in GUIDE, running R2015a. The code below is the callback function that saves the handles.data substructure as a .mat file.

    function save_Callback(hObject, eventdata, handles)
    if CONDITION MET
        filename = handles.data.SaveFileName;
        data = handles.data;
        uisave('data',filename);
        drawnow(); pause(0.1);
        set(handles.Status_Bar,'String','Workspace saved successfully');
        drawnow;
    else
        set(handles.Status_Bar,'String',...
            'Error: Function not available, load data set first');
        drawnow;
    end

    Since this post hasn’t been updated in a while, I was wondering if anything has changed regarding the way the EDT is used? If not, do you have any other ideas as to why this might cause MATLAB to hang? It started happening out of the blue a few days ago, and this code had been working fine (without the drawnow & pause) for months. I can’t give you any error messages and I can’t reproduce the hang reliably, although it does happen on average every 3rd time save_Callback is called. The hang will occur in debug mode as well, as soon as UISAVE is called.

    Thanks for your help!

    PS. The original code was a bit more complicated, it uses UIPUTFILE and SAVE functions to accomplish the same task. But the same problem occurs using both versions, (which I expected since UISAVE calls UIPUTFILE…).

    • @Eric – perhaps your saved data contains some reference (a handle?) to a very large object or data set, and in such cases serializing the data to file could take ages, and would appear as a Matlab hang. You can try to debug what’s inside data and/or replace data with a simple rand(10) to check this hypothesis and/or use ProcessExplorer or one of its kin (e.g. DiskExplorer) to see exactly what goes on when the process appears “stuck”.

    • Eric says:

      @Yair – You are right, data is a fairly large structure, but that doesn’t explain the randomness of the error. If data were truly too large, wouldn’t MATLAB get ‘stuck’ every time (assuming data is the same size every time, which is more or less true)? When UISAVE works, there are no significant timing issues that I could find. In fact

       data = handles.data;

      goes around 2 orders of magnitude faster than

       data = rand(10);

      Moreover, the hang is definitely permanent, and the GUI has never started working again without force-closing MATLAB. (Although I’ve only had the patience to wait 5 minutes).

      I feel like I’m looking in the wrong place for the bug, but I’m not sure where to go from here. Perhaps it’s a java or memory issue? Reading this post and about the EDT sounded like a good place to start. If you have any other suggestions on different workarounds or other thoughts, theories, or musings, I’d love to hear them.

      Thanks!

    • Yair Altman says:

      @Eric – you are missing my point: if your handles.data contains any sort of handle/reference to some class object, then serializing it (which is done when you run uisave but is NOT done when you run data=handles.data) could indeed cause Matlab to hang.

      As I said above, you can also try to use ProcessExplorer and other similar utilities to check whether Matlab is stuck on CPU churning or I/O, and if you drill down then you might get clues as to the source of the issue.

      Another idea is to separate uisave into several independent commands: first call uiputfile to select the target filename, then drawnow; pause(0.01); to clear the popup hang, then call the standard save with the user-selected filename.

      I never said that investigating Matlab hangs is easy…

  14. Ron Knoebel says:

    I think I may have a similar issue but it relates to running a Simulink model from a matlab script using the sim command. It seems like if I am in debug mode I never have any issue and the Simulink model launches and runs fully to completion, but when I run in normal mode the Simulink model will open and hang after just starting the simulation (a few simulation steps). I know that the Simulink models run fine so I don’t think its that the simulation is actually crashing and when I check the task manager it shows matlab is not consuming any CPU. Additionally this whole simulation process is getting called from excel so maybe that adds another layer, but adding a drawnow pause just before the sim command doesn’t seem to make any difference. Anythoughts I why the simulation works in debug mode and when run directly from Simulink, but hangs when being called from sim as part of a larger calling function. Sorry if this is not clear or is not in the right forum, but it seems like a similar issue to me.

    I am using Matlab 2014a 64bit (ver 8.3 Matlab and Simulink), and the Excel is version 2013 that is calling matlab initially to open Matlab, and call functions to initialize and launch matlab sim command…

    • Malcolm Lidierth says:

      Even if MATLAB/Simulink are sharing a JVM (and AWT event queue) they need not share a RepaintManager (which manages the queue and necessarily, therefore, runs off that queue). I have no knowledge of Simulink so this may be nonsense: but is there a drawnow/pause equivalent Simulink-side? If so, you may need to call them, rather than those on the MATLAB-side.

  15. Jay Willis says:

    Thanks. This fix (drawnow; pause(0.05)) still works for me, using R2015b

  16. Shruti says:

    Hi everyone, I have a MATLAB GUI that has a couple of drop-down menus, edit text-boxes, check-boxes and push-buttons.
    Now, I am running a while loop in the background continuously as I need to check if it is midnight. If it is, I perform some functions. The issue is, even though I use drawnow and pause in my while loop, sometimes MATLAB still hangs-up on me and the GUI becomes unresponsive and does not recognize any of the user inputs. Here is the while loop part of my code:

    while stop_timer==0
        pause(0.1);
        drawnow;
        pause(0.1);
        current_time=clock;
        if current_time(4)==0
            post_mortem;
        end
    end

    Does anybody have any solution to this? On searching for answers to previous similar questions, the solution seemed to be to use drawnow and pause, but that doesn’t seem to be working for me either.

    Any guidance would be appreciated.

    Thank you

  17. Joe S says:

    Perfect, thanks! Enjoy a cup of coffee.

  18. g. says:

    Hi,

    I have a similar problem under Linux, Ubuntu 16.04. Matlab hangs up when using the “print” command to export figures. I can not interrupt the software and I have to kill the process.

    My script makes simple 3d graphics and uses some additional functions written by me. What is weird is that the problem is systematic, however, the same functions, used to generate other plots, do not causes any problem. The problem arises with the print command, no matter the option used. Matlab goes in “Busy” state but it allows me to, e.g., edit the script.

    I tried to add before/after the print command the pause and/or drawnow commands but without success as suggested here (.

    uname -a
    Linux laresa 4.4.0-57-generic #78-Ubuntu SMP Fri Dec 9 23:50:32 UTC 2016 x86_64 x86_64 x86_64 GNU/Linux

    ver
    —————————————————————————————————-
    MATLAB Version: 8.3.0.532 (R2014a)
    MATLAB License Number: ••••••
    Operating System: Linux 4.4.0-57-generic #78-Ubuntu SMP Fri Dec 9 23:50:32 UTC 2016 x86_64
    Java Version: Java 1.7.0_11-b21 with Oracle Corporation Java HotSpot(TM) 64-Bit Server VM mixed mode
    —————————————————————————————————-

    Any help is welcome g.

  19. Alex Becker says:

    Hi Yair,
    I have exactly the same problem. All symptoms that you’ve described.
    However I don’t work with modal dialogs. I work with GUI with many different elements (I built it without GUIDE).
    Would you recommend to add drawnow; pause(0.05); to every callback function as a first row right after the function declaration?

    • @Alex – I don’t recommend adding drawnow/pause everywhere, only in those places that you see cause a problem. In most cases you do not need to add it. You probably see that the hang occurs at a specific callback, and I would put drawnow/pause only in that callback.

    • Alex Becker says:

      Thanks Yair,
      the problem is that there are many GUI elements and I don’t know when exactly the matlab hangs.
      I will probably add a logger for each callback in order to find the trouble-making callbacks.

  20. Katie says:

    Yair,

    I’m having a strange issue that may be related to this. I have a complex set of plots that I have grouped, docked, and undocked as a group. Somehow, in this last step, the edit plot tool keeps being turned on. I have it coded to be off and switch to data cursor mode. It did this about 80% of the time I ran the code. With this fix it’s knocked it down to about 30%, but I can’t get it to stop completely. Any ideas what’s causing this?

    By the way, thanks for this amazing site, and the book! They’ve been lifesavers.

Leave a Reply

Your email address will not be published. Required fields are marked *