Best way for a thread to wait without busy-waiting

Hi!
I have a thread that has nothing to do but to monitor the status of a variable
public static boolean askToClose. This variable is set by other
threads to indicate that this thread should stop now. But I don't want the thread
to busy-wait like in this piece of code :
public void run() {
     while (!askToClose) {
          Thread.sleep(1000);
     cleanAndStop();     
}I'm new to Thread programming in Java so I'm not sure what's the best way to wait
for an event without busy-waiting. I've tried using interruption instead of
monitoring for the boolean variable :
public void run() {
     try {
          synchronized (this) {
               System.out.println("WAITING");
               wait(0);
     catch (InterruptedException e) {
          System.out.println("INTERRUPTED !");
     cleanAndStop();     
}and the other threads would simply call myThread.interrupt() instead of setting
askToClose = true;And I've also used a LinkedBlockingQueue :
public static LinkedBlockingQueue q = new LinkedBlockingQueue();
public void run() {
     try {
          q.take();//Waiting
     catch (InterruptedException e) {}
     cleanAndStop();     
}and on the other threads :
MyThread.q.add(new Object());Which one is the best solution ? Do I really avoid busy waiting with this code? Is
there a better way of doing this?
Thx for your help !

Your wait() based solution is OK, except that the other thread should
use
synchronized()
  notify();
}

Similar Messages

  • What's the best way for home sharing to iDevices without iTunes?

    What's the best way for home sharing movies and tv shows on my iDevices?  I know I can use home sharing through iTunes, but I'm looking for a way to share videos to my iDevices without having to leave my computer on.  I have a MacPro, iPhone, iPad, Airport Extreme, and Airport Express (and several external hard drives).  Can anyone suggest an app that would do this?  Can I have videos on an external hd attached to an Airport Extreme/Express and have it stream without iTunes?

    If your "server" is new enough to run Mountain Lion, you can purchase the OS X Server app from the Mac App store and you'll have everything you need to host a NetInstall (NetBoot) server.
    If your machine does not support Mountain Lion, you'll need to purchase the appropriate Mac OS X Server software (i.e. Lion Server or Snow Leopard Server)
    From there you can host NetInstall or NetRestore images, depending on your preferred workflow, which can be created using System Image Utility.
    As Richard points out you can also use Deploy Studio which, again depending on your preferred workflow, might simplify things.

  • Best way for add thousans items to listbox without freezing ui in wpf

    Hello guys.
    What is the best way for add thousands items (or even more) to Listbox without freezing UI.
    I search many post in the web but I don't understand how this posts writer wrote that code.
    I realized that ObservableCollection can contain 1000 items or even more and show that items to listbox just for few second without freezing UI but I don't Know how can I use that!
    Can you guys give me an example.
    thanks.

    If you bind an observablecollection you can add items to that from a background thread.  Then bind that to the itemssource.  I usually new up an observablecollection, add the items then set the bound property to  that.
    But I avoid thousands of items. 
    You should provide some sort of filter mechanism the user chooses a category or whatever and then fill with a maximum of 300 items.
    Users simply can't work with thousands of items.
    It is usually reading the data out  a database which takes the time rather than creating objects to bind.
    Hence this:
    protected async override void GetData()
    ThrobberVisible = Visibility.Visible;
    ObservableCollection<CustomerVM> _customers = new ObservableCollection<CustomerVM>();
    var customers = await (from c in db.Customers
    orderby c.CustomerName
    select c).ToListAsync();
    foreach (Customer cust in customers)
    _customers.Add(new CustomerVM { IsNew = false, TheEntity = cust });
    Customers = _customers;
    RaisePropertyChanged("Customers");
    ThrobberVisible = Visibility.Collapsed;
    That's making an asynchronous entity framework call.
    A list of customers is obtained.
    These are then wrapped in a customer viewmodel each.
    Finally the observablecollection Customers is set to this new collection and propertychanged raised to notify the view.
    The itemssource of a datagrid is bound to Customers.
    Hope that helps.
    Recent Technet articles: Property List Editing;
    Dynamic XAML

  • What is the best way to open emails and attachments without using wifi?

    For I-phone and I-pad, what is the best way to open emails and attachments without using wifi?  I turned off wifi in my settings but my boss thinks there may be another way and a better way to use something else instead of wifi.  Any help would be appreciated!  Thank you!

    Thanks!  That is a very good question you post.  My boss asked me that and I am assuming that he is having issues with using wifi wherever he is at.  My boss is the kind of person that when he asks something you look into it and ask him no questions...he's the only one asking questions!  But thank you for your response I will tell him the information you told me and hopefully that will help!

  • Best way for building an application main frame

    I'm about to program a desktop application.
    The main frame will have menus, toolbar, status bar etc.
    There will be a lot of interaction between the menus, toolbar buttons and other custom gui components (such as an editor).
    My question is which is the best way for building it.
    Cramming all the code in one class file is out of the question.
    I thought about making my own custom JFrame and add API functions like for it so different GUI elements can be accessed.
    Each component which will be manipulated will be in its own class file with the constructor accepting a reference to my custom JFrame object which it is contained in.
    Any suggestions on the matter would be of great help since I've never done extensive Swing programming before.
    P.S.
    The application makes extensive use of RMI.
    What considerations should I take into account (except using SwingUtilities.invokeLater()) ?

    Hi,
    I have replied on this subject somewhere else today but what I do is have one simple entry point where I just instanciate a JFrame.
    On that frame I have a main JPanel. On that panel I add new objects like JPanels, tabs etc.
    I keep each new panel in a separate source as it is easier when the application grows, and it will. That also means that several programers can work with the same application without interfearing each other.
    I hope you understand what I mean the the thing is to split up the code into several sources.
    It may not suit everyone but I found this approach to be the best for me.
    Klint

  • What is the best way to clean ipod touch screen without scratching?

    Best way to clean ipod touch screen without scratching it?

                I have heard screen klean is a great touch screen cleaner. Also, a good rule for touch devices is not to use anything alcohol based!

  • Which is the best way for a called function to identify caller class name.

    Which is the best way for a called function to identify the caller class name .
    1)Using sun.reflect.Reflection from called function
                    Class caller = Reflection.getCallerClass(2);
                    System.out.println("Caller Class Name ::"+caller.getName());2) Analyzing current threads stack trace from called function
                    StackTraceElement[] stElements=Thread.currentThread().getStackTrace();
                    System.out.println("Caller Class Name ::"+stElements[3].getClassName());Is there any alternate ways to achieve the same .Which is the best way ?
    Called function doesn’t have any arguments, I don’t want t pass any arguments from caller function to called function.
    Plz help.
    With kind regards
    Paul

    798185 wrote:
    Which is the best way for a called function to identify the caller class name .
    Is there any alternate ways to achieve the same.SecurityManager
        // 0 is the anonymous SecurityManager class
        // 1 is this class (also works in static context)
        // 2 is calling class
        static Class getClass(int i) {
            return new SecurityManager() {
                protected Class[] getClassContext() {
                    return super.getClassContext();
            }.getClassContext();

  • What is the best way for my partner and I to share our work across computers?

    What is the best way for my business partner and I to share our work (projects, libraries, images) across computers without emailing items?  Is there creative cloud storage place we can share?

    Can't I just purchase the 200 GB storage, throw our photo library in it, share it with her, and have both of our new and future pics dumped into it?  If so, how do I do that?
    The iCloud Photo Library cannot be shared between users, unless you are using the same AppleID.
    You can share selected photos with shared albums:  iCloud: iCloud Photo Sharing FAQ
    Or create a Photos library on an external drive, that you both can access, as described here for iPhoto:   iPhoto: Sharing libraries among multiple users

  • What are the best ways (for best performance) in MII to process the incoming process messages from shop floor systems to SAP ECC 6.0 and vice versa?

    Hi All,
    Can you please suggest to choose the best ways (for best performance) in MII (12.2 on NW 7.3), to process the incoming process messages from shop floor systems to SAP ECC 6.0 and vice versa?
    Thanks

    Hi Surya,
    Best practices for flow of data from ECC --> SAP MII --> Shop floor & Vice verse:
    1. Send ECC data through IDOC's/RFC's as messages to SAP MII message listener and BSL transaction process data and update directly on shop floor database as if you configured in Data services or later send those data by web service to shop floor system (i.e. depends on Shop floor machines).
    From Shop floor:
    shop floor --> SAP MII --> ECC
    1. Use either Web service or fetch data from DB and pass data to BAPI's  for sending to ECC through BLS transaction.
    Regards,
    Praveen Reddy

  • WHat is the best way for other iphone users to share pictures with me?  I am doing a project which req. people to send me 100 pictures at a time that I'll be putting in my iphoto?

    WHat is the best way for other iphone users to share pictures with me?  I am doing a project which req. people to send me 100 pictures at a time that I'll be putting in my iphoto? thank you.

    ingridlisa,
    I'd suggest to ask them to create Shared PhotoStreams and to invite you to view the streams, see:
    iCloud: Using and troubleshooting Shared Photo Streams
    Regards
    Léonie
    Added:
    that I'll be putting in my iphoto?
    Will you be collecting the photos in iPhoto on your iPhone or on a Mac? On a Mac a Shared PhotoStream requires Mac OS X 10.8.2.

  • Acrobat Standard XI, but can only find the CD for windows.  I have a mac (I have access to an external CD drive and I have the product keys for windows).  What is the best way for me to install it?

    Hi, I purchased Acrobat Standard XI, but can only find the CD for windows.  I have a mac (I have access to an external CD drive and I have the product keys for windows).  I have never installed it anywhere else.  What is the best way for me to install it?

    Hi lintonm86921521,
    I can understand your concern & will guide you through this.
    I am so sorry to inform you that Acrobat XI Standard is not available on Mac, you can only use it on your Windows computer.
    You can also refer to the system requirements at : System requirements | Acrobat family of products—older versions (XI, X, 9)
    In case if you have any further query please let us know, we will be happy to help you.
    Regards,
    Aadesh

  • HT4914 I purchased iMatch because my old computer was failing and I was afraid of losing my music library. Now I bought a new laptop; what is the best way for me to transfer my library to my new laptop? Will iMatch help me do this?

    I purchased iMatch because my old computer was failing and I was afraid of losing my music library. Now I bought a new laptop; what is the best way for me to transfer my library to my new laptop? Will iMatch help me do this?

    Is/was failing or has failed?
    If the old computer still runs one of these methods may be best.
    Method 1
    Backup the library with this User Tip.
    Restore the backup to your new computer using the same tool used to back it up.
    Deauthorize the old computer if you no longer want to access protected content on it.
    Keep your backup up-to-date in future.
    Method 2
    Connect the two computers to the same network. Share your <User's Music> folder from the old computer and copy the entire iTunes library folder into the <User's Music> folder on the new one. Again, deauthorize the old computer if no longer required.
    I'd recommend method 1 since it establishes an ongoing backup for your library.
    I don't have personal experience with iTunes Match, but in principle you should be able to download all the tracks currently registered to your iTunes Match account. This isn't quite the same as restoring your previous library exactly as it was. There is always the potential for iTunes match to provide the wrong version of a song and could be content such as movies, podcasts, audiobooks etc. that would have been excluded.
    tt2

  • I am looking to start developing apps for the iTunes Store, but I have no previous experience. What is the best way for me to start on this? As in which programs and materials must I need and what I need to know. Thanks!

    I am looking to start developing apps for the iTunes Store, but I have no previous experience. What is the best way for me to start on this? As in which programs and materials must I need and what I need to know. Thanks!

    You will need a Mac, with OS X 10.6+ on it, to be able to develop iOS apps.
    There is some info on these pages :
    developer site : https://developer.apple.com
    developing for iOS 7 : https://developer.apple.com/ios7/
    developer support : https://developer.apple.com/support/
    developer forums : https://devforums.apple.com/index.jspa (you will need to be a registered developer to access them)

  • Hello, what is the best way for me to convert RW2 raw format for use in Photoshop CC

    Hello, what is the best way for me to convert RW2 raw format for use in Photoshop CC. I would appreciate any help with this.

    Thanks for the quick help. I do have to leave for work. When I try to
    download the images from the camera they seem to only be in jpeg (I don't
    see any rw2 or raw files to download). If I select the jpeg file it seems
    to only download a jpeg file. I do understand that I do have the option to
    open the jpeg in RAW. In doing this, is all the extra information included
    in the RAW file there or is it lost coming from the camera
    Once again thank you for trying to make me understand how this works.
    Have a great day.
    On Sat, Sep 13, 2014 at 12:14 PM, ssprengel <[email protected]>

  • Best way for capturing HDV

    Best way for capturing HDV
    using easy setup setted to HDV1080 50i (camera is a Sony HDV HC1) captured video look like sh...
    and when exported with compressor is worst!
    some idea?

    Ok fantastic ! you are right (the frustration was talking for me)
    video is shooted in 16:9 HDV 1080 50i
    Captured video looks:
    full of orizontal lines (that look like scan lines) expecially evident on figure edges and on motion subjects
    and
    like it was resized 1440x1080i from a different lower resolution
    video is exported with compressor
    MPEG-2 3.7Mbps 2-pass 16:9
    Description: Fits up to 150 minutes of video with Dolby Digital audio at 192 Kbps or 120 minutes with AIFF audio on a DVD-5
    File Extension: m2v
    Video Encoder
    Format: M2V
    Width and Height: Automatic
    Pixel aspect ratio: default
    Crop: None
    Frame rate: (100% of source)
    Frame Controls: Automatic
    Aspect ratio: 16:9
    Field dominance: Auto detect
    Average data rate: 3.7 (Mbps)
    2 Pass VBR enabled
    Maximum data rate: 7.5 (Mbps)
    High quality
    Best motion estimation
    Closed GOP Size: 1/2 second, Structure: IBBP
    DVD Studio Pro meta-data enabled
    In these case the first problem is i can't obtain 16:9 format an the lines becomes more more evidents
    software is Final cut Studio HD
    camera is Sony HDV HC1e
    hope I wrote all the info
    Thx

Maybe you are looking for

  • Material exchane ,copy pricing and conditions from main item to sub item.

    Hi All, We are using parts exchange/interchangeability in the transaction ME22N, While using ME22N we are exchanging  main item with interchangeable part and while doing so we want to copy pricing and conditions from main item to sub item. But its no

  • BP searh help for Bank control Key (with restricted values)

    Hi all Wise men   Please suggest me a way to add search help to screen field (GT_BUT0BK-BKONT) table field( BUT0BK-BKONT ) with values 01,02,03,04,05 in Txn BP. Sorry Iam new to BDT events and BUPT Txn. Also Please suggest to which BDT event can I at

  • Rude and misleading information from the "vendor center".

    I am amazed that Verizon Wireless thinks so little of me, as to let THIS contractor answer questions on their behalf.  I have had a very poor success rate when calling Verizon on the weekends.  Now when I call, first and foremost, my question is, "Ar

  • Hot keys as Access keys

    hi , i want to give HOT KEYS as the access key attribute for my adf faces core components. for example, i have a af:input text field,. i want to keep access key for it as HOT KEY(F1 or any hot key upto F12).. is it possible to keep hot keys as access

  • Trailing Twelve Month Actuals

    We've requirement to calculate trailing twelve month to move data from one region to another. We've Year and Month is two separate dimension where both are level 0. Here is my calc script: FIX ( "US$", "TestCostCenter", "b000", "s000", "Final","TestR