When is it OK for looping while you wait event?

Newbie question: in a world of logic non-blocking, when is it a good idea to loop waiting for something finish?

For example, I am told to check to END_OF_MEDIA (via PlayerListener) to see if a song I played with ToneControl is finished. So is it possible to just create a loop and wait for it be triggered?

Here is a very simple (albeit artificial) example. I want to play a melody (using ToneControl) twice. I play once, wait until it's done, then play again. END_OF_MEDIA tells me it's done. But have I not need to sit in a loop, then waiting for END_OF_MEDIA? Is it OK? It looks bad, but I don't know what would be the 'right' way.

Thank you.

Roricka

The code I used was something called an anonymous inner class Java. Here's another version that does not use this construction somewhat obscure:

void startTune() {    Player p = Manager.createPlayer(...);    p.addPlayerListener( new MyPlayerListener() );    p.start();}

class MyPlayerListener implements PlayerListener {    public void playerUpdate(Player player, String event, Object eventData) {        if (event == END_OF_MEDIA) {            processEndOfMedia();        }    }}

Note This class myplayerlistener is declared inside the MyScreen, right as well as the methods of the class and variable fields. All this has done is to convert an anonymous inner class in an inner class with a name.

Now, it might look like you can move then comes from the MyPlayerListener class in a separate file named MyPlayerListener.java. But this does not work, at least not directly. The reason is related to one of the strange features of inner classes in Java (anonymous or not): an instance of an inner class carries with it an implicit reference to an instance of the containing class. That's why playerUpdate() can call processEndOfMedia() as if it was a MyPlayerListener member function, even if it is a member of MyScreen function. Somehow, an instance of MyPlayerListener lives a dual identity as an instance of MyScreen.

If you want that myplayerlistener has stated in its own file (or if you want her to be a top-level class, not public in MyScreen.java or a static inner class of MyScreen), the rules of the language to say that there can be more than double-identity of nature. At this time, you cannot call the processEndOfMedia() in the same way as a MyPlayerListener instance does not have a reference to an instance of MyScreen. (In fact, it has no way of knowing that processEndOfMedia() is a function in the class MyScreen!) The way out of this is to give MyPlayerListener a way to refer to a particular instance of MyScreen. Here's one way:

class MyPlayerListener implements PlayerListener {    private MyScreen client;    public MyPlayerListener(MyScreen client) {        this.client = client;    }    public void playerUpdate(Player player, String event, Object eventData) {        if (event == END_OF_MEDIA) {            client.processEndOfMedia();        }    }}

Then, back in MyScreen, you need to change the call to the constructor:

    p.addPlayerListener( new MyPlayerListener(this) );

And if you put MyPlayerListener in another package that MyScreen, you must also change the visibility of public processEndOfMedia().

Anonymous inner classes are very convenient for these listener classes little, but they do not have the code a bit difficult to read. Put them in their own compilation units are more work, but it makes the code a little easier to manage, especially when come back you after a few months and try to understand what made you the way back when.

Tags: BlackBerry Developers

Similar Questions

  • ORA-00060: Deadlock detected while you wait the cursor CLOSE resource

    Hello

    I am a new Member of this forum. I work with a problem that we have obtained a few weeks ago. It runs in the lot C Pro executable on 10 threads dealing with > 800 data accessed from more than one table. The error, such as reported was a package.function call.

    This is the error I encountered:
    process_item ~ G *, D * ~-60 ~ ORA-00060: Deadlock detected while you wait resources ~ PACKAGE ERROR = cursor CLOSE C_ * in the R package *. I * 7641

    The slider is a simple SELECT without Table or record locking.

    My questions are:
    * During the occurrence of this error, execution is already in the line of the CLOSE cursor or did the error has occurred between the OPEN and the CLOSE slider? There are several lines of code between the OPENING and CLOSING:
    -one who calls to a package.function that simply stores the values of parameter to a variable
    -another one that retrieves the cursor. The group that contains the values of the cursor is used only by a single function in the package

    * Is it possible for this CLOSE cursor cause a deadlock? What could have caused this?

    * From what I know, Oracle treats blocks by abandoning the blocking process, while others continue, but this impasse caused our program to hang. How is that possible? The origin of the impasse might be our Threading program? This is a rare event and has past that twice this year.

    Thank you
    RAF

    RAF Serrano wrote:
    I see, so it be that blocking has occurred before the CLOSE cursor or it occurred during CLOSING? The cause could be executable ProC

    first cause is NOT ProC

    or is it really an error in PL/SQL

    first cause is NOT PL/SQL.

    cause of ORA-00060 is DML (INSERT, UPDATE, or DELETE)

  • ORA-00060: Deadlock detected while you wait resource

    Hello

    I have a trigger to an underlying table. It fires after that insertion of the events in the underlying table. When I try to update some columns in a table underlying even within the trigger, I get the error below.

    ORA-00060: Deadlock detected while you wait resource

    Can anyone clear or correct me.

    Thank you

    Ignore the Aurélie. It is just a spammer who is trying to promote some criminal website.

    A deadlock occurred if two different sessions lock resources. Each session can wait the other session ends.

    I suppose that you set up a trigger and use the 'autonomous transaction' wrongly to a commit. This function creates a new session. Now you have two (or more) session that could create deadlock. Committing inside a trigger from the table is ALWAYS bad (with some exceptions).

    Solution: remove the pragma of your relaxation. Then the other problems you get with it.

  • Trying to update a "Loading" label... "while you wait for a thread

    Hello, I am new to Java and BlackBerry, so it is a double learning curve for me.  I tried searching for an answer and we have tried a number of things, but I do always get the label that I update to display.  Any help would be greatly appreciated.  I have a main screen with a label field.  I start a thread, and that this thread works I loop and try to update the label as in the httpdemo example.  I do this in refreshMenuItem.  The code looks like she change the label, but the screen does not appear to refresh and show the update label.  Any advice?  Thank you.

    public class testLoadingMainScreen extends MainScreen
    {
    
       private boolean isLoading;
       private LabelField statuslabel;
    
       public testLoadingMainScreen()
       {
    
          LabelField title = new LabelField("Loading Demo", LabelField.USE_ALL_WIDTH);
          setTitle(title);
    
          statuslabel = new LabelField("Waiting...", LabelField.USE_ALL_WIDTH);
          add(statuslabel);
       }
    
       Public void requestSucceeded(final String message)
       {
          isLoading = false;
          updateContent(message);
       }
    
       public void requestFailed(final String message)
       {
          isLoading = false;
          updateContent(message);
       }
    
       private MenuItem _refreshMenuItem = new MenuItem("Refresh List" , 10, 10)
       {
          public void run() {
    
             //setup the status messages.
             String[] statusMsg = new String[6];
             StringBuffer status = new StringBuffer("Loading");
             statusMsg[0] = status.toString();
             for ( int j = 1; j < 6; ++j)
             {
                statusMsg[j] = status.append(" .").toString();
             }
    
             updateContent("Starting...");
    
             isLoading = true;
    
             //start the thread
             try
             {
                  testLoadingThread dispatcher = new testLoadingThread(testLoadingMainScreen.this);
                  dispatcher.start();
             }
             catch (Exception e)
             {
                  System.out.println(e.toString());
             }
    
             //while thread is working, update status message
             int i = 0;
             while ( isLoading )
             {
                updateContent(statusMsg[++i%6]);
                try
                {
                   Thread.sleep(500); // Wait for a bit.
                }
                catch (InterruptedException e)
                {
                   System.err.println(e.toString());
                }
             }
    
          }
       };
    
       protected void makeMenu(Menu menu, int instance)
       {
          menu.add(_refreshMenuItem);
          menu.addSeparator();
          super.makeMenu(menu, instance);
       }
    
       private void updateContent(final String text)
       { 
    
          //synchronized(UiApplication.getEventLock()) {
          //    testLoadingMainScreen.this.statuslabel.setText(text);
          //    testLoadingMainScreen.this.invalidate();
          //}
    
          UiApplication.getUiApplication().invokeLater (new Runnable() {
             public void run()
             {
                testLoadingMainScreen.this.statuslabel.setText(text);
                testLoadingMainScreen.this.invalidate();
             }
          });
       }
    
    }//end testUImainscreen class
    
    public class testLoadingThread extends Thread {
    
        testLoadingMainScreen screen;
    
        public testLoadingThread(testLoadingMainScreen screen) {
            this.screen = screen;
            }
    
        public void run() {
    
            //put thread to sleep so I can test informative labels
            try {
                Thread.sleep(5000);
            } catch (Exception e) {
                screen.requestFailed(e.toString());
            }
    
            screen.requestSucceeded("Sucess");
    
        }//end run
    
    }//end testLoadingThread class
    

    MenuItems run in the UI thread... don't sleep() in them.  I guess that's causing your problem of update to block the UI thread.  Use rather a reason for recall with a background thread making sleep if you need regular notifications to the user interface.

    ~ NN

    Edit: On coffee/reflection, recall patterns may be overkill here... you can simply use a Timer/TimerTask.

  • Indexing for loop while seizing the unique values in table

    Hi all

    I have another question. Overall, I have a table and I want to take each element of this array. My thoughts of how do are the following:

    I use a loop for the indexing of my table. Then I create a local variable outside of the loop in order to get the individual elements of the array. But it does not work I think because the local variable is not updated at each iteration.

    Also, it feels like there is a more elegant way to do what I want to do.

    Can someone give me some advice to solve my problem?

    Thank you very much.

    Best regards

    Tresdin

    I don't know why you are so hung up with a local variable to send sequential orders of VISA.

    Here's what I do:

    That sends commands to the SCPI 7 to my AC source with a delay of 100 ms between each command sent.

  • While you wait for spare camera for 40 days. My k910 has speaker failure. : ()

    What a piece of crap... My k910 start failure involved while I'm waiting for spare camera... Call speaker is ok, but the media here totally dead speaker... It's my problemfull phone I've ever had... My past a706 and my wife s920 are problemless...

    Fortunately after a tried to push both the up and down button of the active again speaker volume...

  • QML pauses while you wait thread.

    I have a connection that the screen when you press the "CONNECT" button, I want the buttons disappear and to display a progress bar.

    My code when you press LOGIN:

    Set the visible property of the button to false and progress bar to true visibility.

    Create a thread and connect to my web service and get the answer.

    Wait thread ends with pthread_join()

    Handle the response and either make visible the new button or go to another part of the application.

    The problem is the button do not disappear or the progress bar appears. They only AFTER the pthread_join().

    Any suggestions on what I can do to fix this? I just want to prevent the user from spamming the "connect" button while he checks the connection information.

    Thank you!

    Updates to the user interface will not happen because you have blocked the UI with pthread_join() thread.

    I did something very similar to the HelloCamera example:

    https://github.com/BlackBerry/Cascades-community-samples/tree/master/HelloCamera

    When the user presses the button "Take a picture", I grey out and start my threads of work (hidden inside the camera_take_photo() implementation).   When one of my sons indicates completion, I emit a SIGNAL which is intercepted by a SLOT function in my application that makes the visible button again.

    I suggest that your button handler marks itself invisible or disabled, creates a thread and not to join this thread.

    Instead, when that thread terminates, it should send a SIGNAL.  While your application has a SLOT Manager related to this signal, which makes the visible button again and joins in your thread.

    In short... SIGNALS and SLOTS is your solution.

    See you soon,.

    Sean

  • I buy photoshop and LR to 9.99 today, so when I have soap operas?, thank you!

    I need help for this info, how can I get the serials for the applications in the creative cloud? Thank you!

    never.  There is no serial number used with subscriptions single user cc.  your adobe id allows you to check your license.

    Install the application of cc, Download Adobe Creative Cloud apps desktop | CC free trial Adobe

    Now you can install lr and ps trial (30 days) while you wait for your payment to process.  Once this has happened, log out and then back to your application of cc to convert test full versions - sign, sign | Creative desktop application Cloud

  • 6700 premium wireless when you sleep for a while doesn't wake up.

    OfficeJet 6700 Premium works wireless.  After he goes to sleep for a while, he doesn't wake up and messages telling me, it's not connected.  I turn on the printer to wake her up, and then turn off and turn it back on and all is well.   If I just turn it on, it still does not print. Have printer set to 15 minutes before going to sleep.  Only when she sleeps for an extended period of time (time or more, or at night) is it that way and I get the offline problem.

    Problems of number of wireless network Test results found. : Diagnostics results are that all pass with the quality of the excellent signal, 1 channel.... Disconnect is the total count of 711, last hour is 3 and disconnect the count in last 24 hours is 24.   The network name is the name of my network, hardware address (MAC is 00: 9 c: 02:0 b: d1:e8 with the IP address: 192.166.1.94, Source of Configuration: manual.) Communication mode: Infrastructure, Auth Type: WPA - PSK, chryptage: Auto (AES or TKIP).  With the help of windows 7 (64 (64 bit) bit) with HP Pavilion P6000 Series, model p6612p,

    After you through your suggestions and following those of others and reading pages of info, I got to the point where I updated the firmware.  When I finished it, he told me that he could not connect wireless and use the USB cable.  After connecting that and feel, I found that I have two 6700's on the computer, a regular and wireless.  When I select the wireless, everything seems (for a day) working as expectred and start perinting even if the printer has been asleep that if it continues, solved the problem.

  • Time for a while loop to run once

    Hello guys,.

    I want to measure the time for a while loop to run once. There is a piece of code raised. So I just created a simple VI to try, please let me know which is the right way to do it?

    And I wondered, when I run the VI without highlighting the execution, he wouldn't give me a number, maybe it's because the code is simple and really fast? I have to highlight all the time?

    Thank you

    Not quite right.  Both get primitive value time will run at the same time.  use an image sequence to force the order of execution, as shown.  I also brought in the relitve of accuracy seconds vi of VI. LIB\utilities because it depends on the clock of the system rather than the mSec timer accuracy.

  • For loop within a while loop

    I have for loop within a while loop... admission to the for loop N comes from the VI selection... the while loop I a condition essentially statement it stops just after to finish all the iteration in loop...

    Entrance to the N loop is bascially driven by a local variable... that's the problem Iam having:

    When I press the Start button to run the program... regardless of the output of the select VI is gives the N of the for loop, then the loop starts and then ends in place... and when the output of the select statement takes a different value (the N of the loop for) loop not work until I restart the program again... What can I do so that the for loop runs again for another value of N, the RUN program button is enabled.

    1. clean your diagram.  Style guides suggest keep the pattern of a single screen.  With a little effort, I was able to get your DB less than 1600 x 1000 pixels.

    2 then I can see (some) it happens all at once. This thing does nothing?

    3. local variables can lead to race conditions.  Output in Angle position may be a race condition, although is probably not what you wanted to do.  What does the wired local time at the moment present terminal meter? (Ooops! Two controls with the same name - which can be quite confusing as well!)  If you need or want two components of façade having the same text, use the legends.  Make the labels is different so the comic is more readable.

    4. having more than one Dequeue function on the same queue will lead to unpredictable results.  When an item is removed, it is removed from the queue and is not accessible to any other Dequeue function.  In parallel loops, you have no way of guessing which Dequeue will seize any particular element.

    5 use Boolean reverse instead of Select with wired False to true and true cable at the entrance to false entry. Better, just make the case of forgery in the structure of the case within the for loop the real deal. No required reversal.

    6. I was not looking for to determine the logic of the code within the structure of this case. It seems I could have posted a much simpler way to do this several weeks ago.

    7. use multiply from the Digital Palette rather than a node form multiply by 4 or 1.8. Uses less space BD and is much easier to read.

    8. as has been suggested, learn how to work the machine architecture and the State of producer/consumer.  They can make your life much easier.  Do not try to convert immediately to these models.   It's too much bite to at some point.  Learn how they work first.  Make a few simple examples.  Then rewrite this program in this format.  Probably faster than fixing what you have now.

    Lynn

  • loop for and while loop with empty table entry

    Hello

    I have a question with loop and loop.

    When a constant empty array (zero element) is connected to the loop For with "allowing the index", there are no interactions performed in loop For. But, if the loop is replaced by any loop, no problem.

    LabVIEW 2010

    Hello

    It is ok. I have no problem at all.

    For the 'loop' For when you connect the table thanks to indexing, the number of iterations is set to the size of the array. The iteration number assigned to N (in your case 10) is ignored.

    For the 'While' loop the number of iteration is defined by the Boolean Condition and the size of the array is ignored.

    Paul

  • for loop in while loop

    To all,

    I have a question, I have a loop within a while loop. The loop runs and displays the log data. It seems that, until I have stop the while loop that log data display. It almost seems that the for loop runs until the while loop is stop.

    The following accessory is an example of what I have in my code. But the because the loop runs in this example. My code is the same idea, but the loop seems to run when I start my program with execution of climax. Otherwise, it runs once I left the while loop.

    All entries?

    Thank you

    Cosmica

    I tried your VI and there is nothing wrong the way in which it executes. Nothing happens until the second tab is selected and you press the 'off' button, date on which the loop FOR runs until the indicator shows a "9". In subsequent runs, again, it count up to nine, but it is so fast that you never see. For the observer, the indicator remains at nine.

    Of course you would see things a little bit better if you place the small waiting inside various parts of loops. At present, the VI consumes all CPU do nothing but turn empty loops for always while spending from time to time some nanosecods to iterate through the loop FOR. You also destroy your resource VISA with tunnels of default output, so the fence at the end probably will fail. Overall, the code seems too complicated for what you want to do. Do you really need to link a case control tab structure? Seems unnecessary. The for loop should run when the button is pressed, since this implies automatically that Your ' e on the second tab, you don't need to read the tab control. It's redundant!

  • What happens when you specify multiple iterations of the parallel loop that you have processors?

    I have an app that does the same things together up to 10 times for different material resources. For example, I have a list of 10 COM ports I want to send orders series. I want that they be executed as close to synchronous as possible, but up to 200 ms sync would be acceptable. Currently, I use a loop set up to 10 parallel iterations and assume that LabVIEW will juggle processors according to the needs, the iterations run it as simultaneously as possible. Experimentally, LabVIEW indeed seems to create 10 parallel loops, even when running on a computer with only 4 logical processors, otherwise you go 10-element inside the loop would only be not able to complete, right?

    My question is, I'm doing something verboten with my number of iterations of the loop? According to the help of LabVIEW for loop iteration parallelism dialog box: "If you plan to distribute the VI on multiple computers, set number of instances of parallel loop generated equal to the maximum number of logical processors, you wait for one of these computers contain never.» Clearly I'm violating this opinion and yet it seems to work. My performance will essentially be the same as if I had 10 blocks of code in parallel on the block diagram?

    "Reading'how many Threads don't LabVIEW allocates?" links to this page, it seems that, at worst, LabVIEW is hungry for thread and switching of threads between iterations, but my short demand slowing down enough to accommodate this suboptimal situation. At best, LabVIEW has allocated 4 threads per the enforcement system, so as long as I have at least 3 processors, there are at least more son than the parallelized loop iterations. It's all a bit confusing.

    RnDMonkey wrote:

    I have an app that does the same things together up to 10 times for different material resources. For example, I have a list of 10 COM ports I want to send orders series. I want that they be executed as close to synchronous as possible, but up to 200 ms sync would be acceptable. Currently, I use a loop set up to 10 parallel iterations and assume that LabVIEW will juggle processors according to the needs, the iterations run it as simultaneously as possible. Experimentally, LabVIEW indeed seems to create 10 parallel loops, even when running on a computer with only 4 logical processors, otherwise you go 10-element inside the loop would only be not able to complete, right?

    My question is, I'm doing something verboten with my number of iterations of the loop? According to the help of LabVIEW for loop iteration parallelism dialog box: "If you plan to distribute the VI on multiple computers, set number of instances of parallel loop generated equal to the maximum number of logical processors, you wait for one of these computers contain never.» Clearly I'm violating this opinion and yet it seems to work. My performance will essentially be the same as if I had 10 blocks of code in parallel on the block diagram?

    "Reading'how many Threads don't LabVIEW allocates?" links to this page, it seems that, at worst, LabVIEW is hungry for thread and switching of threads between iterations, but my short demand slowing down enough to accommodate this suboptimal situation. At best, LabVIEW has allocated 4 threads per the enforcement system, so as long as I have at least 3 processors, there are at least more son than the parallelized loop iterations. It's all a bit confusing.

    In this case (where you're interacting with the external hardware and have an appointment) there will be a delay of inheirant at each iteration.  THUS, "Oversubscibing" or by allowing the parallel proceedings as logical processors, actually improves performance by running another period of waiting during the iteration.  In fact, you're not "Violate the advice" of oversubscibing.  You use this technique correctly! Just may not have read about this.  See Esp PP 4

  • I have not connected to hotmail for a while, 3 months or more, and when I did there is absolutely nothing in my Inbox unless the Hotmail team welcome. Where all my stuff?

    lack of everything in my email account

    I have not connected to hotmail for a while, 3 months or more, and when I did there is absolutely nothing in my Inbox unless the Hotmail team welcome. Where all my stuff?
    That's happened?

    Darling
    Just a step: none forum available choices apply to this question.

    Hello CherieBurns,

    The best place to ask your question of Windows Live is inside Windows Live help forums. Experts specialize in all things, Windows Live, and would be delighted to help you with your questions. Please choose a product below to be redirected to the appropriate community:

    Windows Live Mail

    Windows Live Hotmail

    Windows Live Messenger

    Looking for a different product to Windows Live? Visit the home page Windows Live Help for the complete list of Windows Live forums to www.windowslivehelp.com.

Maybe you are looking for

  • DAQmx loop

    Hello everyone. I have 2 questions. 1. when I do a continuous supply with DAQmx, I put a DAQmx read in a while loop. I can't understand why I can't put all the codes DAQmx in a while loop. 2. what type of data it carries the 'task' to 'work out '? I

  • Convert 1 d table in Numeric then back to table

    Hello, I have a 1 d array that contains the following elements: Item 0 = MSByte of register chip (U8) Element 1 = LSByte of the register of chip (U8) What I want to do is take this table 1 d convert it to a digital representation as follows: Example,

  • OfficeJet 6500 black ink

    I have a HP Officejet 6500 wireless that does not print color only black ink Solutions/similar problem?

  • Media Player sync

    Windows Media Player has encountered a problem during the synchronization of the file to the device.

  • Name of scheduled report

    Hello We did a custom report for UCCX8.5, that we wish to plan. This report can show the details of a CSQ, by selecting a filter CSQ. For this reason, we need schedule a new task for each CSQ. Here the question arises: when I look at the overview of