Updating frame content between Thread.sleep() calls

I have several JLabels in a Frame. What I want is to update the content of the labels (to be more precise, the ImageIcons), but with pauses in between each update (lets say 1 second). So, I want to change the content of one label, have those changes show on screen, then, wait for a second and change the content of the second label, show the changes, wait for a second, change the next label, and so on...
What I'm doing is:
change label 1
Thread.sleep(1000);
change label 2
Thread.sleep(1000);
change label 3
Thread.sleep(1000);
...And the problem is that the individual changes are not shown on screen until the whole process has finished. It does pause after each change, but the change to the particular label is not shown afterwards. Then, when the whole process is finished, the changes to all the labels are shown simultaneously on screen.
I have tried calling repaint() and validate() after each call to Thread.sleep(), but it makes no difference.
Why are the changes not updated on screen until the end?
How can I achieve what I'm trying to do?
Many thanks in advance.

You're sleeping in the main thread, so you're holding up the paint thread too...
I'd trying extending each label / visual component, to include it's own timer and thread.
eg. ( not compiled nor tested, but addresses all the main points... )
regards,
Owen
public class myLabel extends JLabel implements runnable
    boolean animate = true;
    Thread paintThread;
     public myLabel ( )
          super();
          paintThread = new Thread ( this );
     public void startAnimation ( )
          if ( animate == false )
             animate = true;
             paintThread.start();
     pubic void stopAnimation ( )
         animate = false;
     public void run ( )
           while ( !animate )
               Thread.sleep ( 1000 );
                final Runnable runnable = new Runnable()
                    public void run()
                          // change label text
                          // Make any Swing / GUI changes here                      
                    } // run
               };    // runnable
               // force/flag this label as requiring a repaint
               invalidate();              
               // NB : You must use this to avoid multi-threaded problems with Swing
               SwingUtilities.invokeLater(runnable);
}

Similar Messages

  • Update jLabel in between Thread.sleep()'s

    I have multiple Thread.sleep()'s in my code under a jButton actionevent evt.
    In between these, I need to be able to update a jLabel, but for some reason it waits until the last thread.sleep() before it updates the jLabel.
    Any ideas why?
    private void jButtonActionPerformed(java.awt.event.ActionEvent evt) {
       try {
          Thread.sleep(1000);
          jLabel.setText("Change Text To This");
          Thread.sleep(1000);
       } catch (InterruptedException ex) {}
    }So rather than waiting 1000ms, then update label, then wait another 1000ms, it just waits 2000ms, then updates the label
    Please help!
    Thanks

    Edward9 wrote:
    I am new to Java and I just cannot work out the tutorials,Hard luck then.
    the code behind my applet doesn't matter as long as it works,Which it will, of you code it correctly after learning from the tutorials.
    I have spend 6 months on this appletWould have taken much less time to learn to do it correctly.
    and everything worksBy your definition of "works"
    apart from this one problem --> jLabel to update between thread.sleep()'s.Easy when you know how.
    Its all I need to do and my project will be over and I can get away from Java.I have a suggestion: why don't you get away from Java right now, take the failing grade you've earned, and get on with your life. Really.
    Is there absolutely no way it can be done?Already covered above and in previous responses.
    I was told the jLabel will not update until the thread is free to do so, so i will need to look up on multiple threads,No, you need to go through the Swing tutorials.
    i have tried to but none of it makes sense to what i need done.Give up. Now.
    db

  • Difference between thread.sleep and BufferedReader.readline()

    Hi All,
    I have J2SE application which is infact a listener, to keep it working for 24/7 what you people suggest do i use
    while(true)
    Thread.sleep(10000);
    or
    BufferedReader br = new BufferedReader( new InputStreamReader(System.in));
    System.out.print("Enter Quit to Exit.. ");
    String cmd = br.readLine().trim();
    if (cmd.equalsIgnoreCase("quit"))
    System.out.println("Quitting...");
    System.exit(0);
    Please also suggest which one is optimized solution.
    Regards,
    raza

    emmi@java wrote:
    HI,
    My application is J2SE based not web based.
    RegardsSorry, could have sworn I read J2EE.
    In any case, a thread is exactly what you want. And neither "sleep" nor "readline" but a simple wait().
    Edit: And, yes, the real question is, as already asked, what do you mean by "listener"?

  • Difference between LockSupport.parkUntil and Thread.sleep method

    Hi
    Could someone please explain the difference between LockSupport.parkUntil and Thread.sleep methods.
    Thanks in advance.

    javaLearner wrote:
    The thing that I am trying to understand is - the difference / correlation between the two methods mentioned.
    In the javadoc, there is a mention of correlation between the LockSupport methods park, unpark and the Thread methods suspend, resume - but not park and sleep.Then that suggests that there isn't any difference /correlation -- whatever you meant by that. Perhaps your question is like asking for the difference between a fish and a bicycle.
    Also, I would like to understand the statement
    These methods are designed to be used as tools for creating higher-level synchronization utilities, and are not in themselves useful for most concurrency control applications. (from the javadoc)Again, you're going to have to explain what you don't understand about it.

  • 10 ms overhead when calling Thread.sleep on Linux

    Hi,
    I have been working on a traffic shaping simulation that requires me to send packets on a ms basis. When I call Thread.sleep(11) on Linux 2.4, I get a constant return around 30 ms. I tried to bypass the Thread.sleep function and called directly the select() function under linux with a timeout of 11 ms then I get a constant return around 20 ms. Then if I create a test.c program that loop 100 times calling the select(11), I get a very accurate rate around 10-11 ms. Anyone knows where that 10 ms overhead comes from? I tried executing the java program with Thread.sleep and the -XX:ForceTimeHighResolution but it doesn;t seem to change anything ! Any info would be very welcome ! Thanks

    Actually I get this behavior only on a machine with kernel 2.4. On a different machine with kernel 2.6 I get an accuracy of 10ms for a select call with 10 ms timeout. I know there was some improvements on the jiffy for kernel2.6 but I still don't get why calling select timeout 10ms from a C program return an accuracy of 10ms on linux 2.4 and the same select() timeout 10ms called from java return an accuracy of only 20 ms on kernel 2.4..... :( still looking

  • What's wrong to put Thread.sleep in a session bean?

    i am working on a trading platform and i think there is a design flaw. The part i am working on is the Order Management module. When an order value object is published to a JMS topic and picked up by a MDB. The MDB, in turn, calls a session bean (could be stateless, I didn't check), OrderEngineBean. After this bean saves the order vo into database and broadcast the message to all involved parties, it suspends for 12 sec, using Thread.sleep, so other parities might have a chance to update the vo. If no update occurs, the order is considered expired and abandoned.
    It looks awkward to me to use a Thread.sleep in a session, but I haven't come out with a better idea to deal with the scenario like above.
    Anyone can help me out?
    Thanks a lot!
    Sway

    Setting the property "max-beans-in-free-pool" is not the answer to this issue. By setting this property to 1, the container merely instantiates and keeps one instance of the bean in the free pool at the "start" of the app server. But if the container comes across more than one requests for the same EJB simultaneoulsy, then it will create new instances at that time to handle the requests simultaneously.
    You are seeing intermixed log messages between two threads because these messages are being logged from two different instances of the EJB and NOT the same instance of the EJB. The container does synchronizes the calls on "a method" on "a instance". So what you are seeing are the messages coming from "a method" on "two different instances" of the same EJB.
    You can refer to the EJB 2.0 specification section 6.11.6 Non-reentrant instances for details about simultaneous access to the same session object.

  • Easy updating of picture with threads --- should finish today

    Hi!
    I am really thankful if you can help me.
    My program is supposted to show a clickable picture of number one and if you click the picture it should change to number two.
    If you run this program clicking will not work.
    I try to reference to the old picture by
    JComponent sourceEvent = (JComponent)e.getSource();
    sourceEvent.add(panel2);Perhaps this is not the most elegant way to do it but since I am very slow in programming I would like use at least something similar approach.
    So I have created picture by using labels and panels and I would like to update their contents.
    Later I would like to add parallel playing of midi notes in to my program.
    I am happy if you can also give some advice how to add this midi playing in synchronous way to these threads.
    Thank you very much
    Partly functional source code:
    import java.awt.*;
        import java.awt.event.*;
        import java.awt.datatransfer.*;
        import javax.swing.*;
    import java.io.*;
    import java.util.Scanner;
        import java.lang.Math.*;
    public class Saiekokeilu extends JPanel implements MouseListener  {  
              JPanel panel;
       public static void main(String[] args) throws IOException
           javax.swing.SwingUtilities.invokeLater(new Runnable() {
              public void run() {
                 createAndShowMyGUI();
       private static void createAndShowMyGUI() {
           JFrame frame = new JFrame("Saiekokeilu");
           frame.setExtendedState(Frame.MAXIMIZED_BOTH);
           frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
           JComponent newContentPane = new Saiekokeilu();
            newContentPane.setOpaque(true);
            frame.setContentPane(newContentPane);
            frame.pack();
            frame.setVisible(true);
       public Saiekokeilu() {
           super(new GridLayout(0,1));
           ImageIcon icon = new ImageIcon("num_1.gif");         // huom. icon     
           JLabel label = new JLabel();
           label.setIcon(icon);
           JPanel panel = new JPanel();
           panel.add(label);
           add(panel);
           label.addMouseListener(this);
    void eventOutput(String eventDescription, MouseEvent e) {
    System.out.println("testing" + e.getSource());
        public void mousePressed(MouseEvent e) {
                 ImageIcon icon2 = new ImageIcon("num_2.gif");         
                  JLabel label2 = new JLabel();
                  label2.setIcon(icon2);
                  JPanel panel2 = new JPanel();
                  panel2.add(label2);
                  JComponent sourceEvent = (JComponent)e.getSource();
                      sourceEvent.add(panel2);
                     panel2.updateUI();
                  e.getComponent().getClass().getName().add(label2);
            eventOutput("Mouse pressed (# of clicks: "
                    + e.getClickCount() + ")", e);
        public void mouseReleased(MouseEvent e) {
            eventOutput("Mouse released (# of clicks: "
                    + e.getClickCount() + ")", e);
        public void mouseEntered(MouseEvent e) {
            eventOutput("Mouse entered", e);
        public void mouseExited(MouseEvent e) {
            eventOutput("Mouse exited", e);
        public void mouseClicked(MouseEvent e) {
            eventOutput("Mouse clicked (# of clicks: "
                    + e.getClickCount() + ")", e);
    }   // end class Saiekokeilu

    do what he says.
    1) make your label variable a class variable so that your mouse events can "see" it. That way you can update the label's icon inside the mouse click event.
    2) I'd do the same with the JFrame so you can repeat a "pack()" command after updating the icon. I assume the pictures are different sized and pack will adjust the size of the frame accordingly.
    3) I'd make an array of Strings of path-file names to your pictures. (I called mine imageStrings). I'd also have an int var called imageCount that would be used as an index to this array. Every time you click on the panel, imageCount increments (mod it by the array.length to allow it to loop back to zero) and create a new icon from the imageStrings[imageCount].
    Good luck

  • One thread adding/updating value  and other thread getting values....issue

    am using a spring bean (singleton) and this is how it looks like
    public class MySingletonService {
    private Map<String, List<TaskVO>> alerts = new HashMap<String, List<TaskVO>>();
    //spring will call this method every 15 minutes
    public void pollDatabase() {
    //initialize the alerts instance variable and create/fill the alerts instance variable with new alerts for the employee(from database) .The key for the hashmap is the employee id
    //some client code (e.g. GUI) will call this method to get the alert for the operator id.This can be called anytime to get the latest info from the alert Map
    public List<TaskAlertVO> getOutstandingAlerts(String operatorId) {
    return alerts.get(operatorId);
    The issue here is that when getOutstandingAlerts is invoked by a thread,some other thread(Spring) calling the pollDatabase method might be updating the value.Please give me some idea and solution to get around this issue.
    I was thinking of creating a copy of alerts instance variable in the getOutstandingAlerts method and then use the copy to find the key and return the alert for that operator id.This way we dont have to worry about data conflict.
    Please advice

    Manjit wrote:
    jtahlborn wrote:
    if the pollDatabase() method is getting a complete new copy of the alerts every time, and the alerts map isn't being modified at all after load, then you can just:
    - make the alerts member variable volatible
    - create a new HashMap each time pollDatabase() is called, fill it in, and then assign it to the alerts member variable. Jtalhorn,I think I got your point.Basically you are suggesting that by creating a brand new map in each pollDatabase operation, then I dont have to worry about get operation ,simply because the client code is still looking at old memory location(old copy) and hence should not worry about values getting changes by pollDatabase method.
    I got it.
    But the small doubt is that why even I should bother about making the instance variable volatile ? Your suggestion should work without making it volatilebecause volatile ensures correct memory visibility between threads. if you didn't use volatile, then a caller to getOutstandingAlerts() could see some partially initialized/corrupt version of the map.

  • "Portable" way to do message passing between threads?

    (I posted this on the Apple Developer Forums already, but since that forum is only accessible to registered and paid iPhone developers, I thought it would be nice to put it here as well so as to get some more potential eyeballs on it. I apologize if this kind of "cross-posting" is not kosher/is frowned upon around here.)
    Hey everybody,
    "Long-time listener, first-time caller," heh.
    I've been working for the past 2-3 months on my very first iPhone app. Actually, what I've been working on is a framework that I plan to use in an iPhone app of my own but which I am also trying to write for the "lowest-common-denominator" so that I (and others) can use it in other apps written for both Mac and iPhone.
    Not only is this my first time writing an iPhone app, it is my first time writing for any Apple platform. In fact, it is my first time using Objective-C, period. I cannot stress this enough: I am a "n00b." So go easy on me. I also have not worked with threading before this, either, on any platform, so the learning curve for me here is rather significant, I'm afraid. I am NOT afraid of either taking the time to learn something properly OR of rolling up my shirtsleeves and working. However, on account of my experiences so far, I am finding myself (not to flame or anything!) quickly becoming frustrated by and disillusioned with not so much Objective-C itself, but the Foundation frameworks.
    So with that said, read on, if you dare...
    The basic idea behind my project is that the framework I am writing will present an API to developers which will allow them to write client apps that interact with a particular network appliance or network-aware embedded system. I already have my basic set of classes up and functioning, and the framework works to my satisfaction both on MacOS and iPhoneOS. The platforms I am targeting are MacOS X Tiger 10.4 and later, and iPhoneOS, and up until this point, I've managed to keep a codebase that works on all of the above.
    What I wanted to do next was add some multithreaded goodness to the mix. (Woe is me.) I have asynchronous network socket I/O working within the main thread, and it, in fact, works a treat. In my test app on the phone, I've managed to keep the UI nice and responsive by using the main thread's runloop efficiently. But even though TCP async I/O works fine within the main thread, I want to be able to split out and offload the processing of any data received by the app from the appliance to its own thread. (It is possible, and even desirable, for an application using this framework to be connected to multiple appliances simultaneously.)
    My idea, in order to try to keep things as simple and as clean as possible, was to implement a wrapper class that presented my other main class as an "actor." So, rather than instantiating my main class, one would create an instance of the wrapper class which would in turn control a single instance of my main class and spawn its own thread that the network connection and all data processing for that particular connection would run within.
    (I hope I'm making sense so far...)
    Out of the gate, writing a subclass of NSThread sounds like the logical design choice for an "actor-type" thread, but because I was trying to maintain Tiger compatibility, I stuck with +detachNewThreadSelector:etc.
    Once I decided to pursue the actor model, though, the main problem presented itself: how to best pass messages between the main thread and all of the "actor" threads that might be spawned?
    I stumbled upon -performSelector:onThread:withObject:, and knew instantly that this was exactly what I was looking for. Unfortunately, it doesn't exist on Tiger; only its much more limited little brother -performSelectorOnMainThread:withObject: does. So I kept looking.
    All of the pre-Leopard documentation, tutorials, and sample code that I read indicated that to pass messages between threads, I needed to basically pretend that the threads were separate processes and use the expensive Distributed Objects mechanism to get messages back and forth. Unfortunately, even if that WAS a desirable option, iPhoneOS does not have any support for DO! Grrr...
    Finally, I thought I found the answer when I ran into a third-party solution: the InterThreadMessaging library from Toby Paterson (available @ http://homepage.mac.com/djv/FileSharing3.html). In this library, the author basically implemented his own version of -performSelector:onThread:withObject: called -performSelector:withObject:inThread:. Sounds close enough, right? And actually, it is pretty darn close. It's made to do exactly what it sounds like, and it does it in a platform-neutral way that works on pre-Leopard systems as well as iPhoneOS, using Mach ports instead of DO.
    (...wellll, ALMOST. I discovered after I built a small test app around it that it actually isn't "iPhone-clean." The author used an NSMapTable struct and the NSMap*() functions, which don't exist in iPhoneOS, and he also implemented the handlePortMessage delegate method, but although iPhoneOS has NSPort, it DOESN'T have NSPortMessage. GAAARGH. So I took the time to replace the NSMapTable stuff with NSValue-wrapped objects inside of an NSMutableDictionary, and replaced the handlePortMessage method implementation with a handleMachMessage method, which took some doing because I had to figure out the structure of a Mach message, NO thanks to ANY of the available documentation...)
    Once I started using it, though, I quickly discovered that this implementation wasn't up to snuff. My "actor" class and my main thread will be passing a ton of messages to each other constantly whenever there is network activity, and with InterThreadMessaging, I found that whenever activity started to ramp up, it would collapse on itself. This mostly took the form of deadlocks. I found a note that someone else wrote after experiencing something similar with this library (quoted from DustinVoss @ http://www.cocoadev.com/index.pl?InterThreadMessaging):
    "It is possible to deadlock this library if thread A posts a notification on thread B, and the notification on B causes a selector or notification to be posted on thread A. Possibly under other circumstances. I have resolved this in my own code by creating an inter-thread communication lock. When a thread wants to communicate, it tries the lock to see if another thread is already using the InterThreadMessaging library, and if it can't get the lock, it posts a message to its own run-loop to try again later. This is not a good solution, but it seems to work well enough."
    So I tried implementing what he described using a global NSLock, and it did help with some of the deadlocks. But not all. I believe the culprit here is the Mach ports system itself (from the NSPortMessage documentation for -sendBeforeDate:):
    "If the message cannot be sent immediately, the sending thread blocks until either the message is sent or aDate is reached. Sent messages are queued to minimize blocking, but failure can occur if multiple messages are sent to a port faster than the portís owner can receive them, causing the queue to fill up."
    InterThreadMessaging in fact calls -sendBeforeDate: and exposes the deadline option, so I tried setting a really short time-to-live on the Mach messages and then intercepted any NSPortTimeoutExceptions that were thrown; upon catching said exceptions, I would then re-queue up the message to be sent again. It worked, but Performance. Was. A. Dog. At least the message queue wouldn't be full indefinitely anymore, causing the main thread to block, but during the whole time that these messages were expiring because the queue was full and then being re-queued, either the main thread was trying to send more messages or the actor thread was trying to send more messages. And as far as I can tell, the Mach ports queue is global (at the very least, there is seemingly only one per process). The message would get through with this model...eventually.
    JUST IN CASE the problem happened to be something I screwed up as I was rewriting portions of the InterThreadMessaging library so that it would compile and work on the iPhone SDK, I substituted in the original version of the library in my Mac test app to see if any of these problems became non-issues. I found that both versions of the library -- mine and the original -- performed identically. So that wasn't it.
    Finally, in frustration I said, "screw it, I'm going to try it the Leopard way," and replaced all of the method calls I was making to InterThreadMessaging's -performSelector:withObject:inThread: with calls to Foundation's native -performSelector:onThread:withObject: instead, changing nothing else within my code in the process. And wouldn't you know: IT WORKED GREAT. Performance was (and is) fantastic, about on-par with the non-threaded version when only dealing with a single connection/instance of my class.
    So, in the end, I was able to do nothing to salvage the InterThreadMessaging implementation of cross-thread method calling, and as far as I can tell, I'm out of (good) options. And thus my mind is filled with questions:
    How is the Leopard -performSelector:onThread: method implemented? I'm guessing not using Mach ports, given that I didn't have the same blocking & deadlocking problems I had with InterThreadMessaging. Is it possible to re-implement this Leopard+ method in a similar manner as a category to NSObject under Tiger? Or is it possible, perhaps, to increase the size of the Mach ports queue so that InterThreadMessaging works at a sane level of performance? Or -- I'm getting desperate here -- is there any way that I could trick -performSelectorOnMainThread: to target a different thread instead? (I am assuming here that -performSelectorOnMainThread is implemented under-the-hood much like the new -performSelector:onThread: is implemented, but with a hard-coded NSThread pointer built-in to the code, and that the new method just exposes a more flexible interface to what is basically the same code. I'm probably wrong...) Is there another third-party library out there that I've missed that fits my requirements for being able to do message-passing between threads in an efficient and portable manner?
    I refuse to believe that there is no way for me to maintain compatibility with all of the platforms I wish to support without having to resort to making preprocessor #ifdef spaghetti out of my code. And there SURELY has to be a better way of doing cross-thread message passing in Tiger without using Distributed Objects, for Pete's sake! Is this really how people did it for years-on-end since the dawn of NeXT up until the advent of Leopard? And if there really, genuinely wasn't another alternative, then what is up with the lack of DO in iPhoneOS?? Does Apple seriously intend for developers who have good, solid, tested and working code to just chuck it all and start over? What if there was some aspect of DO that previous implementations relied upon that cannot be recreated with simple -performSelector:onThread: calls? (I don't know what those aspects would be...just a hypothetical.) I mean, I can understand needing to write new stuff from scratch for your UI given how radically different the interface is between the Mac and iPhone, but having to reimplement back-end guts such as something as elemental as threads...really?!
    I do laud the inclusion of the new method in Leopard as well as the new ability to subclass NSThread itself. But for those of us that need to support Tiger for one reason or another, some of these restrictions and omissions within iPhoneOS seem like rather pointless (and frustrating) roadblocks.
    As I hope is obvious here, I have tried to do my homework before throwing up my hands and pestering y'all. If you have the patience to deal with me, please tell me what I am missing.
    Thanks for taking the time to read,
    -- Nathan

    Thanks again for your patience. Comments below.
    etresoft wrote:
    It is pretty unusual that anyone would want to call perfomrSelector on any thread other than the main thread.
    What I described in my original post was not a worker thread, but an "actor."
    It is hard for me to answer this question because there are so many options available to do "message passing". The fact that you think there are so few tells me that you really aren't sure what you need to use.
    I didn't say there were few options for message passing. I said there were few options for message passing that fit my criteria, which are that any potential solutions should both A) work efficiently and with good performance, and B) be available both pre-Leopard AND on the iPhone. -performSelector: ain't available before Leopard. Distributed Objects is overkill. Kernel Mach messages apparently have a high overhead, too, as my experience with the third-party library I wrote about in my original message shows.
    ...consider notifications.
    I thought notifications couldn't be posted across threads, either. How do I post a notification to another thread's default notification center or notification queue from a different thread?
    The notification center is owned by the process. Each run loop can listen for just the notifications it wants. You don't "pass" or "send" notifications, you run then up the flagpole for all to see.
    I am aware of how to use notifications. The documentation for NSNotificationCenter clearly states that "In a multithreaded application, notifications are always delivered in the thread in which the notification was posted, which may not be the same thread in which an observer registered itself."
    So, again, I don't see how one thread can post a notification in such a way that the observer's registered method is executed in another thread (posting notifications "across threads"). This probably isn't a big deal if you are using mutexes (assuming you don't actually care which thread carries out the task associated with the notification posting), but as I said before, this is not what I'm after.
    I don't know what you are really after.
    Allow me to attempt to explain a second time, in a more concise fashion.
    My app will have multiple, persistent TCP connections open, one connection per remote device. The user will be able to select a task to execute on a particular device that we have a connection open to, and get back from the application real-time updates as to the progress or results of the execution of that task. In certain cases, the length of the task is infinite; it will keep executing forever and sending back results to my application which will update its display of the results every second that ticks by until the user STOPS that particular task.
    This can be done simply using async I/O in the main runloop, sure. But if I were going to thread this so that I could be processing the results I've received back from one *or more* remote devices while also doing something else, given that I will only have one (persistent) connection open to any given remote device that I'm interacting with (that is to say, I won't be opening up a separate TCP session for every single task I want to execute on a single device simultaneously), it makes sense _to me_ to implement this as I've described: with every connection to each remote device getting its own thread that lasts for the lifetime of the TCP session (which could be the entire time the application is running, times however many devices the user wishes to be connected to while in the app). I won't be spawning a new thread for every task the user wishes to ask a remote device to do.
    This is why (I think) I need bi-directional messaging between the main thread and each of these threads dedicated to a given remote device that we have an active session with/connection to. The main thread needs to be able to tell remote device X (which already has a running thread dedicated to it) to do task A, and then get real-time feedback from that remote device so that the main thread can be displaying it to the user as it is coming back. Same with remote device Y running task B, simultaneously. At any time during the execution of these tasks, the user needs to be able to tell my app to stop one of these tasks, and the main thread needs to send that message to one of the remote devices via that device's dedicated thread.
    This is why I am talking about this in terms of the "actor model," and not the "worker thread model," because the former model seems to fit what I want to do.
    -- Nathan

  • Mouse events during Thread.sleep

    hi.
    I have an applet .
    I have a alghoritm simulator.
    Everytime I find a solution I call the method Thread.sleep .
    I want to pause the application and I create a JToggleButton Pause .
    When I press the Pause during sleep mouse event are managed at the end of alghoritm.
    How can I manage mouse events during sleep?

    All UI events (such as mouse events) occur on the event dispatch thread (EDT).
    That means if you sleep on the EDT, you lock up the UI. For this reason, you shouldn't be sleeping on the EDT.
    I'm not sure what your sleep is trying to do but you need to manage your threads a little more carefully. For instance, any time consuming process which is invoked as a result of a UI event needs to be fired on a new thread to prevent the UI freezing. The fun starts when you have to update the UI as a result of that process, because you should then hook back onto the EDT to avoid the risk of deadlock.
    Some utility classes are provided, such as SwingUtilities, and other example code is provided on Sun's site, such as SwingWorker - but if you do much UI work you'll probably end up with your own core set of threading tools and so on to make life easier.

  • [svn] 3127: Updating asdoc to replace the avmplus call with new set of java files.

    Revision: 3127
    Author: [email protected]
    Date: 2008-09-05 14:16:53 -0700 (Fri, 05 Sep 2008)
    Log Message:
    Updating asdoc to replace the avmplus call with new set of java files.
    Removing all files related to asdochelper.
    QA: Yes, also please test on non windows platform.
    Doc:
    Tests: checkintests, asdoc
    Reviewed by: Pete Farland
    Modified Paths:
    flex/sdk/trunk/asdoc/templates/ASDoc_Config_Base.xml
    flex/sdk/trunk/asdoc/templates/asdoc-util.xslt
    flex/sdk/trunk/modules/compiler/build.xml
    flex/sdk/trunk/modules/compiler/src/java/flex2/compiler/asdoc/AsDocAPI.java
    Added Paths:
    flex/sdk/trunk/modules/compiler/src/java/flex2/compiler/asdoc/AsClass.java
    flex/sdk/trunk/modules/compiler/src/java/flex2/compiler/asdoc/AsDocHelper.java
    flex/sdk/trunk/modules/compiler/src/java/flex2/compiler/asdoc/AsDocUtil.java
    flex/sdk/trunk/modules/compiler/src/java/flex2/compiler/asdoc/QualifiedNameInfo.java
    flex/sdk/trunk/modules/compiler/src/java/flex2/compiler/asdoc/SortComparator.java
    flex/sdk/trunk/modules/compiler/src/java/flex2/compiler/asdoc/TopLevelClassesGenerator.ja va
    Removed Paths:
    flex/sdk/trunk/asdoc/templates/asDocHelper
    flex/sdk/trunk/asdoc/templates/asDocHelper.linux
    flex/sdk/trunk/modules/compiler/asdoc/

    I had a generic record class that has a HashMap to hold the data fields (...)
    method called createRecord() for each record type which would populate the HashMap with the correct data fieldsI'm not sure I understand: are the contents of this field map the same between two records of the same type? Then yes, you don't need to clone the map per record instance.
    one thing that needs fixing is the fact that each time the createRecord() method is called I'm creating a new fieldMap to define the dataFields in the record class.Probably, but that will only get you a little bigger files; you won't gain an order of magnitude on the size of files. The problem for huge files is that as soon as their content is bigger than the available memory, you'll run into problems. A more radical approach if you need to address huge files is to process the records on the fly, and not load all records in memory. Of course not all algorithms or business logic can afford that...
    I know I could rewrite the code and create a class for each record type and declare the fieldMap static but I was wondering if anyone had any better suggestions The Record instance could receive and keep a reference to its RecordType instance, and ask the RecordType instance the DataType for a field's name. That way the RecordType encapsulates the map, and there's less risk that a clumsy other class modifies the static map.
    before I go rewriting a load of code.A load of code?!? Even with the idea of the static map, you only have to edit the enum type (well more accurately, each RecordType enumerated constant's createRecord() method).

  • ConfigMgr 2012 Update Source content deleted

    Greetings,
    I am experiencing a problem that is appears to be the same as the old thread here:
    http://social.technet.microsoft.com/Forums/en-US/bee18ffb-f779-4aa4-900d-046e7711424c/sccm-2012-source-content-gets-deleted?forum=configmanagergeneral
    Rather than revive an old post, I thought it best to start my own.
    We have a rather large environment (CAS +5 Primaries + Many DP's) and we are currently adding several new remote DP's each week. Each time a new DP is added it is placed in a Distribution Group and the "core" package content is sent
    to it.
    I have a problem where my Windows Update Packages keep failing due to content disappearing from the source folder location. This started some time ago, and is now becoming a regular event to correct. Not every day, but once a week or so.
    The Update group has the updates all showing as "downloaded"
    I have a report query that matches the updates to the "GUID" subfolder so I know all the content is there
    I distribute the content from the CAS. Distrmgr.log shows all is good. Packagemgr.log on the Primaries show all is good
    Client have been installing the updates as expected so the deployment does work
    Days/weeks later, ALL the DP's will show as "failed" for that update package. Checking the distmgr.log shows that it is failing to distribute due to a missing source folder. I use my query to work out which update that subfolder GUID belongs to,
    but it is already flagged as downloaded, and when trying to download it again CM just "skips" it thinking it already has the content in that package.
    The "fix" is to download the same update to a new package instead. CM then does a proper check, realises it doesn't have the content and will download the update to the new package source location. I can then copy the missing GUID subfolder
    from the new package into the original package and try the distribution again.
    The problem now is that there are usually many folders missing, so distmgr.log will fail again on the next missing folder. Because it stops at the first error, repeating the above process is incredibly tedious when there are a lot of missing folders.
    My current "solution" is to select ALL the updates that should be in the current package and download them all to a "Temp package" that isn't deployed or distributed anywhere. Then in future when the main deployment package fails, I just
    "select all, copy" the contents of the temp folder into the original folder (skip duplicates) and it puts back all the missing content and distribution will work again.
    We are not using ADR's for this content, although I do have an ADR for the Endpoint updates which go into a completely different distribution package.
    *Something* is cleaning up or purging these folders from the source location, but I have no idea what process or mechanism this might be.
    Any thoughts or suggestions most welcome.
    Scott.

    I've found the cause, blog post write here:
    http://kickthatcomputer.wordpress.com/2014/10/11/configuration-manager-update-source-content-being-deleted/
    Microsoft was working with me trying to identify what was deleting the folders, however nothing was appearing as the cause.
    I just realised this morning that I had used the built-in CM12 Migration function some time back to migrate update packages and groups over to our second hierarchy but hadn't updated any of the migrated content since then. The migrated packages on the second
    hierarchy still point to the same source location and so whenever my original hierarchy added content to the update packages, the second hierarchy would delete it because it though it was "orphaned" content.
    This is something people will have to watch out for when using the migration wizard as the same type of issues will impact things like WIM boot image packages as well where the source content can be manipulated directly by the CM12 system on one hierarchy
    without the other one being aware of that change.
    At the moment the options are to either
    Make sure you run a "migrate changes" job whenever you make changes to updates on your source hierarchy to keep them in sync
    Manually make a copy of the source content to a different folder or location, then update the package source location on the migrated packages to point to that new content (undesirable for massively large content)
    Create a scripted method to schedule regular migration jobs between the hierarchies (looking into this option now)

  • Transfer SLD content between SLDs in SLD 640

    Is it possible to transfer content between two SLD systems in SLD version 640?
    1.) I have  a SLD (call it sldA) that contains the ABAP and JAVA data about DEV and QA system.
    2.) I have another SLD (call it sldB) that contains the ABAP and JAVA data about my Production systems.
    I'm running SLD version 6.40.0 - not 700.
    Is there a way to get the content of sldA into sldB and keep it syncronized? I'd like to maintain two distinct SLDs, but I'd like sldB to have information about the entire landscape. This would be a one way push from sldA to sldB. I'd like this to be an automatic process, not something I have to do manually.

    Though I have not worked on such environment. Your query looks interesting...I tried to find something related.
    About SLD I am sure you must be aware of "SLD Bridge Forwarding" , It exists in 700 and 6.40 as well...
    Is it possible to transfer content between two SLD systems in SLD version 640?
    As per the  [SLD6.40 Post Installation |https://websmp102.sap-ag.de/~sapidb/011000358700001149582007E] Document I think it is possible.
    You might have already checked this document, If not please check page 12.
    It says you need to check gateway connections & RFCs and also need to update CIM contents.(Note 669669)
    To forward data from QA& DEV to Prod - Configure the bridge between this and If you do not want to receive data from ABAP systems in your SLD, set the parameter StartRfcServer to false.( Check this [Link|http://help.sap.com/saphelp_nwpi71/helpdata/en/43/da21ba13660aa5e10000000a1553f6/frameset.htm])
    I think this will make your process automatic from sldA to sldB and also you will get entire landscape information in sldB (Correct me if I am wrong)
    Let us know if it was helpful....
    Cheers

  • IPhone - Trying to Update View from Separate Thread

    I am having trouble updating a view. My iPhone project is built from the Utility Application template. Upon startup, the Main View is loaded and some network communications are performed (on a separate thread). In response to the reply from the network, the toggleView method is called to switch to FlipSideView.
    This works (view changes) when I call toggleView from applicationDidFinishLaunching or by pressing the "i" button on the MainView. When I call toggleView after getting a response from the network, toggleView is called (as evidenced by a NSLog called within the toggleView method) but the View does not update.
    Does anyone have any ideas why this would happen?
    Could it have anything to do with the fact that I'm calling toggleView from another thread? If so, why would toggleView be called but not work?
    Thanks in advance,
    Daedalus
    - iPhone SDK Beta 8

    Update... I figured it out.
    To anyone else seeing this, when communicating between threads, you need to use the NSObject method performSelectorOnMainThread.
    Thanks.

  • How could stop this thread that calls an externall function ?

    Hi all.
    i need an help about syncronization of two thread.
    the first one is smt like that
    Thread t = new Thread(new Runnable() {
                   public void run() {
                        long startTime = System.currentTimeMillis();
                        while (System.currentTimeMillis() - startTime < lifetime) {
                             if (c.dynamic) {                    
                                  c.adjustLayout();
                             c.repaint();
                             try {
                                  Thread.sleep(delayMillis);
                             catch (InterruptedException ex) {
                                  // ignore
              t.start();where c.adjustLayout(); & c.repaint(); are syncronized over a astructure called G using syncronized(G)
    now the second thread is:
         Thread t = new Thread(new Runnable() {
                   public void run() {
                        long startTime = System.currentTimeMillis();
                        while (System.currentTimeMillis() - startTime < lifetime) {
                             if (c.updateVisible) {
                                  c.updateVisibleGraph();
                             try {
                                  Thread.sleep(delayMillis);
                                  Thread.yield();
                             catch (InterruptedException ex) {
                                  // ignore
              });where the function c.updateVisibleGraph(); is syncronized over G as well. the problem is that this function, takes seconds, and block thread A and B (both of them ar suyncronized, so if B is running A cannot run).
    how can i stop c.updateVisibleGraph(); in the middle of the exectuion or each 50ms.
    is this possible?
    thanks
    Edited by: ELStefen on 26-ago-2010 16.08
    Edited by: ELStefen on 26-ago-2010 16.11

    isocdev_mb wrote:
    Using a synchronized-block is not designed to give up the lock for little while, it holds the lock until the block ends. Your requirement needs a far more fine-grained approach, quite different from your sketched implementation.
    It would involve quite an amount of guessing of what's behind the G and c your mentioning to suggest a way out. Please elaborate on what you're trying to achieve so that we can suggest how to do that...
    P.S. this forum likes problems to come with a simple working example, which you did not provide and a description of what you'd like to achieve, some context.as i thought, damn.
    Well give a working example is quite complex for the time being. Is a big project and take out this part is quite complex. But i can explain the goal.
    Practically there's a Graph (G)
    this graph is used by 2 thread, one is the update the edges and vertices, adding and removing them. the other one thread is the painter of the graph.
    the problem is when the first thread is updating the structure of G, sometimes this operation takes time (seconds) and being synchronized on G it blocks the paint thread as well.
    the thing that i would like to have is keep the painting working each tot millisecond. the updating thread works when necessary. if the update operation takes to long, it has to be stopped in the middle (and it has to restart after the paint) in a way that the paint thread can be executed.
    as the code is, and as you said, synchronizing the entire block code cannot works as i want.
    is this more clear? any clue about how can i solve this?
    many thanks
    Edited by: ELStefen on 27-ago-2010 12.43

Maybe you are looking for