Sleep or wait() / notify()  Which is better IYO

Consider an app where a central object, like an information server is handed a query and an amount of time will pass before that information is available. For caching, many objects may ask the same question and be waiting on the same answer. Is it better to have the queries do a sleep loop to wait for the response or is it better for the queries to register with the server and call a wait(), then have the server issue a notify to objects that were waiting?
Thanks for the advice.

Thank you. I like sleep as well. Although with three little ones that can be a difficulty.
I am having a difficulty with how to implement the wait notify. Can you tell me if the following is a good / bad / normal / horribly wrong example?
// sorta code...
// This class goes to a central location
// or the network for an answer.  It represents one answer for one query.
class InfoServerQuery extends Thread{
  volatile boolean isComplete = false;
  volatile String response = null;
  Vector pool = new Vector();
  public synchronized boolean isReady(Object obj){
    if(!isComplete){
      // Add object to answer pool
      pool.add(obj);
      return false;
    }else{
      return true;
  public void run(){
    try{
      // Get the information.......
      response = getInfo();
      // set isComplete
      isComplete = true;
      // notify all that are waiting.
      for(int a = 0; a < pool.size(); a++)
      synchronized(pool.get(a)){pool.get(a).notify();};
    }catch(Exception e){
      throw new RuntimeException();
// This class asks the questions.
class QueryClient{
  // instantiated in constructor
  InfoServerQuery q;
  public String getAnswer() throws Exception{
    while(!q.isReady(this)) synchronized(this){wait();};
    return q.response;
}Thanks for any insights.

Similar Messages

  • Which is better notify() or notifyAll() ??

    Hello ,
    i know that notify() is responsible to wake up on of the threads waiting to access object and notifyAll() responsible to wake up all threads waiting to access same object but what it is the other different between these two methods ?? and which is better ??
    Thanks a lot

    If there are n number of threads in a wait() mode then the notify() method wakes up or sends the notification to the nth thread that went in the wait() mode in the last. So, only the last thread that went into the wait() mode wakes up out of all the waiting threads. However, in case of notifyAll() the notification is sent to all the waiting threads that are waiting. So, any one of them may come out of the wait() mode depending upon the priority and other factors, like the kind of multitasking supported by the operating system( preemptive or collaborative).

  • Which is better... Sleep or shutdown?

    Which is better for your computer... sleep or shutdown?
    Thanks

    Technically, it doesn´t matter much if you shut your computer down or just put it to sleep., i.e. nothing is more detrimental to your computer´s "well-being" than the other, respectively.
    I´m not sure about the Sleep Mode with the iMac, but I believe it´s a suspend-to-ram, right?
    That would mean any unsaved data isn´t saved and could get lost if the computer fails to wake up from sleep.
    That could be a point against making the computer sleep.
    When it´s sleeping, the computer will also consume a steady, albeit very low quantity of electrical power. From an energy-saving standpoint, that could also be counted as a negative aspect.
    MacBooks and MBPs use suspend-to-disk as sleep mode, which means the contents of the ram is saved onto the hard drive and then the computer is fully turned off. Takes a bit longer than suspend-to-ram.
    I always put my computers to sleep... both my iBook G3 and my Win laptop.
    My win laptop will automatically enter suspend-to-disk after 2 hours if it isn´t used again by then.
    hth
    ibook g3, acer travelmate w/ pentium m 725   Mac OS X (10.3.9)  

  • Which is better for computer and program... sleep or turn off?

    When not using, which is better for the program, sleep or turn off the computer and any explanations are welcome...

    I advise shutting down rather than sleep. A good shut down often clears up nascent problems, and of course you're saving electricity by not running your machine and also saving those precious MTBF hours on all the mechanical components. Think of the hours it would sleep vs. the number of hours you actually use the machine. Even though sleep consumes less electricity, it still consumes.

  • When in transport, which is better have the MBP shut down or sleep mode?

    when in transport, which is better have the MBP shut down or in sleep mode?

    Read the user manual that came w/your computer.  Personally, I shut down when transporting.  
    It all comes down to personal preference.  "Different Strokes For Different Folks"

  • Wait/notify, await/signal, faster blockingqueue that scales with N threads

    Hi,
    I have been benchmarking a blockingqueue. It holds 100 items before writers block. It uses not-empty/not-full semaphores. Typical stuff.
    I have noticed that with 1 writer and 1 reader threads, using synchronized()+wait/notify is faster than reentrantlock+await/signal.
    I tried to find the point (in number of W/R threads) where reentrant lock is better.
    For the remainder os the discussion, I must say that I never use 'fair' rentrantlocks: I tested them and they are always slower than synchronized.
    So, I always use 'unfair' locks.
    The thing is, the tests results are messed up. I mean I would expect a monotonous progression in reentrant lock performance as the number of W/R threads is increasing. But the reality (on a dual core dual opteron) shows strange progressions. Without diving into numbers...
    I would like to hear about the experiences of other people relatively to:
    -queue implementations and readers semaphore, writers semaphores most efficient patterns.
    -scalability observations and implementation choices related to the number of threads to be concurrent.
    Of course I have been experimenting with notify()/signal() instead of notifyAll()/signalAll() in order to avoid waking up too many writers/readers that do not stand a chance to perform their enqueue/dequeue without going back to wait()/await() again (in my case, fairness isn't an issue for readers, and for the moment, I accept unfair enqueue from writers). Also, a reader can notify/signal not only a waiting writer but another waiting reader if the queue isn't empty after its own dequeue. I'm about to do the dual notify/signal for writers: not only notify/signal a waiting reader but also another waiting writer if the queue isn't full after its own enqueue.
    Of course, this good-intentions implementation ends up notifying/signaling a lot. I'm searching for a new way of thinking, in case I have been blinded by too much obsession on my current implementation...! :-)
    Thanks.
    PS: for those of you that wonders why I don't use j.u.c array blocking queue, that's because I need:
    a) many queues enqueue to be able to notify/signal a single thread (1 thread waiting to read many queues). This implies an externally plugged-in readers (not-empty) semaphore.
    b) enqueueMany(array), dequeueMany(int max) ->array

    In Java 5 ReentrantLock provides much better performance under contention than built-in sync. Conversely built-in uncontended sync is always much faster. In Java 6 contended built-in sync has pulled back some ground on ReentrantLock. So with only two threads it is not surprising that built-in sync is faster.
    So the switch over point depends on the level of contention. This is a function of the number of threads (and CPU's) and what they do while holding the lock and between holding the lock.
    For evaluating read/write synchronization you need to have a read operation that is relatively long to dominate the cost the heavier read-lock. You also need sufficient parallelism to allow enough concurrent readers to make overall reader "throughput" significant.
    Benchmarks are seldom that useful/insightful unless realistic access patterns and workloads are used.

  • Which is better an android or apple

    Which is better getting an android smart phone or an Apple I Phone?

    As the poster Horses 547 said its a matter of personal preference. However I own and use both. Printing via air print is smooth and easy on an iphone. Printing on a android phone is iffy and tedious and you will have to find an app to print since there is no native app to do so. I purchased http://www.printhand.com which costs around $12 from the app store. but it is in my opinion the best printing app out there for android. I use it on my android tablet as well and its great. This company is the maker of the print app on iphones.
    The iphone is a little harder to put your own ringtone on the device. However very easy from the Itunes you put on your computer and hook into.
    Another thing an iphone does is if you use their cloud service or pay for a song it is available on all your ios devices. Iphone, ipad, or ipod or up to five computers registered through itunes on those computers.
    Google play music also can sync with all your android devices.
    Iphone don't have external Micro SD card slots, so the storage on the phone is all you have.
    Iphones use imessage which does not count against your text allotment  to another iphone or ipad user. it send regular text to non iphone users.
    Another thing is Face Time but I found a better program called oovoo at http://www.oovoo.com or in the Google Play Store for free.
    Iphones are paper thin but I have an android that has a larger view area and is also paper thin and light. Depending on the android phone it may have a removable battery, whereas iphones are sealed as are some new androids. I have found the sound for music better on my iphone, and videos are crystal clear. Again on some better androids the music and video is comparable .
    There is really not many differences but it up to the user.
    One last good thing is iphones are updated via Apple, no long waits for OS updates like is done with Android devices, and android devices on Verizon.

  • Which is better, a G4-450 Dual or a Mac Mini 1.42?

    which is better in terms of Sequencing and plug in performace, the G4-450 Dual or a Mac Mini 1.42?

    G4-450GHz Dual with 896MB RAM
    Mac Mini 1.42GHz with 1 gig of Ram
    G4-450GHz Dual gets more instances with plugs, more tracks and performance then the 1.4GHz 17" Powerbook, 12" powerbook and Mac Mini which all have the same G4 processor.,
    Today, i took the same 34 track session,
    -all 34 tracks have a Logic Comp, Eq, Gate
    -and also 8 Buses with Comp, EQ, Gates, Delays, Flange, Phasors, Pitch Shifters, 2 Reverbs (1 long and 1 plated) as well as some other toys.
    -Master with Waves Ren Comp, Logic EQ.
    -6 esx24 Instruments with high loads ( Harps, Strings, Cellos, Drums and Perc)
    -8 Long (16 Bar) drum tracks ( Bass, HH, Snare, Toms, Overheads, Fills, Percussion dubs)
    -4 Vocal takes and Dubs (more then 16 Bars long)
    -Bass Track
    -2 Acoustic stereo tracks
    -4 Guitar tracks, dubbs and fills
    -4 Slide Acoustic guitar tracks
    -4 dubbed effect vocal tracks
    AT first, he G4-450GHz Dual choked with 2 errors, then it buffered into the session well and played everything back fine of the same FW drive.
    The mac mini got major problems and only performed 28 tracks with the esx24 tracks frozen, and from time to time after heating up chokes again, i had to wait a few minutes before i bounced the session due to overload errors.
    Over all, Both have G4 Processors and about 1GIG ram (450GHz Dual is under 1 GIG), but its a clear fact that double processors win, even the lowest 450GHz Dual is still hotter then any flashy fast Bused mac mini, powerbook or iMac.

  • Which is better, Double Buffering 1, or Double Buffering 2??

    Hi,
    I came across a book that uses a completely different approach to double buffering. I use this method:
    private Graphics dbg;
    private Image dbImage;
    public void update() {
      if (dbImage == null) {
        dbImage = createImage(this.getSize().width, this.getSize().height);
        dbg = dbImage.getGraphics();
      dbg.setColor(this.getBackground());
      dbg.fillRect(0, 0, this.getSize().width, this.getSize().height);
      dbg.setColor(this.getForeground());
      paint(dbg);
      g.drawImage(dbImage, 0, 0, this);
    }that was my method for double buffering, and this is the books method:
    import java.awt.*;
    public class DB extends Canvas {
         private Image[] backing = new Image[2];
         private int imageToDraw = 0;
         private int imageNotDraw = 1;
         public void update(Graphics g) {
              paint(g);
         public synchronized void paint(Graphics g) {
              g.drawImage(backing[imageToDraw], 0, 0, this);
         public void addNotify() {
              super.addNotify();
              backing[0] = createImage(400, 400);
              backing[1] = createImage(400, 400);
              setSize(400, 400);
              new Thread(
                   new Runnable() {
                        private int direction = 1;
                        private int position = 0;
                        public void run() {
                             while (true) {
                                  try {
                                       Thread.sleep(10);
                                  }catch (InterruptedException ex) {
                                  Graphics g = backing[imageNotDraw].getGraphics();
                                  g.clearRect(0, 0, 400, 400);
                                                    g.setColor(Color.black);
                                  g.drawOval(position, 200 - position, 400 - (2 * position), 72 * position);
                                  synchronized (DB.this) {
                                       int temp = imageNotDraw;
                                       imageNotDraw = imageToDraw;
                                       imageToDraw = temp;
                                  position += direction;
                                  if (position > 199) {
                                       direction = -1;
                                  }else if (position < 1) {
                                       direction = 1;
                                  repaint();
              ).start();
         public static void main(String args[]) {
              Frame f = new Frame("Double Buffering");
              f.add(new DB(), BorderLayout.CENTER);
              f.pack();
              f.show();
    }which is better? I noticed smoother animation with the later method.
    Is there no difference? Or is it just a figment of my imagination??

    To be fair if you download an applet all the class files are stored in your .jpi_cache, and depending on how that game requests its graphics sometimes they are stored there to, so really if you have to download an applet game twice, blame the programmer (I've probably got that dead wrong :B ).
    But, what's wrong with Jars. They offer so much more.
    No offence meant by this Malohkan but if you can't organize your downloaded files the internet must really be a landmine for you :)
    Personally I'd be happy if I never seen another applet again, it seems java is tied to this legacy, and to the average computer user it seems that is all java is capable of.
    Admitidly there are some very funky applets out here using lots of way over my head funky pixel tricks, but they would look so much better running full screen and offline.

  • Which is better Apple Ear Pods vs. In Ear Earbuds

    So which is better? I can't really tell the difference because there like the same. Unless I'm not paying attention to the bass and tremble.

    Haven't tried multiple EAR files before but encountered constraints when using one EAR file.
    For example, we may need to wait for another colleague to complete his portion on programming so that we can proceed to implement the entire EAR file. Is this also a constraint for multiple EAR files application ?
    If we can separate the EAR files into different modules, different colleagues can work on different modules concurrently. It could be more efficient... Is that the case ??

  • Advice Needed... which is better?

    Hello...  I am not a computer 'genius", but not a complete "computer idiot' either.  I have a question, and then I will give my reasoning, because maybe it matters in the decision.
    Which is better, a PC (Gateway) with 6GB Ram, i5 processor, 1.5TB HD  or an Imac 4GB Ram, i3 processor, 1TB HD??
    Basically, I have had a Dell 2GB Ram desktop for 7 years, which suited me fine. I ran CS3 on it with no problems.  I recently had a virus, and had to swipe my computer, and when I re-installed Adobe, my Premiere Pro will no longer allow me to edit properly (audio plays fine, while video lags and skips around during viewing).  I know it is time to get a new computer either way, and a few friends have told me that I really shouldnt be running Premiere Pro on 2GB of ram, and suggested at least 6GB.
    I found a Gateway for $650 on bestbuy site with the above specs... but then someone I know, told me I would be better with an Imac with the specs above.  Is that possible that a 4GB mac would run better than the 6GB PC?
    also..  will CS3 work on the Windows 7 PC, but if I get Mac system I will be using CS5.
    I use Photoshop, and Premier Pro for simple music video editing (5-6min videos).  I do not do anything major..but want to at least be able to view what I am doing.
    thanks

    While I don't agree that Macs are as inferior as some here claim, for your purposes an i5 iMac is certainly inadequate. The i7 quad core iMac is something else again; it can take up to 16GB of RAM, which is plenty for most applications. The particular i7 CPU in the iMac is also quite capable with a number of performance enhancing technologies on board. The big problem with the iMac, though, is that it comes with only one internal HDD; there is an added SSD option, but in my opinion it's still too expensive. For video you should have at least two internal drives and preferable three or four, as others here have said. External drives are generally slower, even if you use a FireWire 800 port. Sometime this year Apple may add a Thunderbolt port to the iMac, as they have to the MacBook Pro. This will be a game changer for external media, with unheard of flexibility in connectivity and the performance of Fiber Chanel at an affordable price. There are already external RAIDs coming to market with Thunderbolt connections. However, there is no date certain for such an iMac refresh.
    For even semi-serious video you need some heavy iron, whether Mac or PC. There are some great Mac Pros available now with up to 12 cores on two 6 core Intel Westmere processors; however, even though I am a Mac fan, I'm sure you can build or get a BTO Windows PC with comparable specs for less. I suggest a minimum of four modern CPU cores to handle multi-threading and multi-tasking chores. At least two fast internal hard drives, four is preferable. And, of course, the more RAM the better, though this too will raise the price. You may not get the maximum RAM right away; the important thing is that the motherboard be able to support substantial RAM upgrades so that you can grow into it.
    The challenge, even with PCs, is that a number of core technologies are changing right now. SixGb/s hard drives are becoming available but it would take a high-end and relatively new motherboard to support them properly. So, besides the question of which computer to get, you have to consider when to get it. If you need it right now, that narrows your choices somewhat because you cannot wait for these new technologies to come on line.
    The most important thing to consider, though, is not to cheap out. Presumably you will be doing some real work on it, so think of this computer as an investment in your own future. Buy the most computer you can afford and a little bit more. Oh, and there is a new Version of Final Cut Pro coming out soon that will be Intel only and 64 bit capable, so Apple is moving ahead on this front, too. Remember, not all of Adobe's CS apps are 64 bit yet either. It's just one more technology in transition.
    One point I will concede, however, is that Windows has better video drivers than OS X. Even on a Mac, running Windows in Boot Camp delivers better video frame rates than the Mac versions of the same apps running in OS X. So, for reasons of cost and better video support, a Windows PC is probably the way to go. PCs also have it over Macs in the number of options available. If you are not a techie yourself, I agree as well that it is probably a good idea to have someone who is built it custom for you. Of course, with a custom PC you won't get the kind of warrantee that comes from Dell or Apple, but the person who builds it for you will probably be able to service it as well.
    Ultimately, of course, your budget is likely to govern the kind of PC you get more than your preferred specs. But even with Windows PCs you get what you pay for. A cheap PC is just that, a cheap PC. Inexpensive PCs are affordable because they use inferior components. Keep that in mind.

  • Which is better for solving Mac issues

    I have been experiencing Kernel Panics and program crashes. I want something that is good for testing hardware and OS issues. Can either of these find corrupted data files? I am looking at two utilities for purchase. Which is better for solving Mac Issues?
    TechTool Pro
    or
    Disk Warrior?

    When you say "complete bootable backup" do you mean that it contains the OS + all my applications? Basically a clone of the start-up?
    Yes, you have that very clear. I use Tri-backup or CCC for this normally, but there are other options.
    If I have this clone, and I start getting issues on my Mac, I can Zero the HD and reinstall the OS via the clone (including all the applications)?
    Yes, and if pressed for time you can just keep working off the Clone.
    I can Zero the HD and reinstall the OS via the clone (including all the applications)?
    Yep, right back to 100%, excluding HW issues.
    With all my software... it takes a day to reinstall all of it to a complete image.
    Yes, the only sensible thing is a Clone... or two. Most problems can be overcome by simply Verifying/Repairing the HD once in awhile, Repairing Permissions before and after every update/upgrade, and turning off Auto Updates in SW Update CP... wait a couple of weeks and check these forums for the number of problems with any update.
    PS. DiskWarrior has saved me hundreds of times from having to do complete new Installs or cloning back of Installs, I figure that's saved me 10's of thousands of hours & grief... I appreciate Alsoft so much that I don't even go for the generous upgrade offers on new versions... I just buy the new version completely at Retail.
    PPS. Funny thing, you'll read something like DiskWarrior is a one Pony Dog Show or something... just does one thing... I just have to laugh outloud... Yeah, the one thing is... cure my incurable Mac Problems 99.9% of the time!

  • Why do we need to take a lock before invoking wait()/notify() on an Objec

    Hi,
    Why do we need to take a lock before invoking wait()/notify() on an Object? i know that we shud take otherwise illegalstateexception is thrown.
    what is the reason to take a lock bfefore invoking the above methods. why does jvm expects from the programmer?
    Cheers,
    duggana.

    Well, very often a wait or notify is conditional on the state of some flag (semaphore) which is protected by the monitor. By putting the wait in a synchronized section you guarantee that the sempaphore won't change between the final test of it and the actual wait or notify, otherwise a notify might be lost and the program hang.
    // wait on semaphor
    if (!canProcede)
       synchronized(this)
           if(!canProcede)
              wait();
    //   release semaphor
    synchronized(this)
         if(!canProceed) {
              canProede = true;
              notify();
        }If the wait above wasn't guarded by the sychrozined it's possible the second code fragment might be executed between the test and the wait, in which case the wait would be called after the notify and, hence, wait for ever.

  • Under CentOS 6 x64, Java Thread.sleep()/Object.wait() will be influenced.

    Under CentOS 6 x64, Java Thread.sleep()/Object.wait() will be influenced while changing OS time.
    I found a BUG in java bug list. The bug id is 6311057 with fixed status. But I find it still existing.
    Under CentOS6 x64 platform, on JDK1.6.0_33, the bug still exists.
    But under CentOS5 x64 platform, on same JDK, the problem does not exist.
    Could anyone give me help? Thanks.
    The bug's link is http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6311057
    Edited by: user10222290 on 2012-6-13 下午9:22

    user10222290 wrote:
    One server could want to synchronize it's OS time with another server when they connected each other for some business reasons. I have 3 computers running pretty much continuously with time synchronised from one of the internet time servers. They never seem to be more than about 1/10 th second apart and any time corrections are very very small.
    Some threads have started to run before changing OS time, so these thread's sleep process will be influenced sometime seriously.I understand that but I would only expect this to be a problem when there is a significant change to the OS time. If each server is synchronized to a time server then the time corrections will be very very small.
    If OS time was turned back some days, these thread could not wake up untill some days passed.Agreed but why would the "OS time be turned back some days" ?
    This whole problem seems to me to arise because the servers are not time synchronized. Now I understand that there may be concerns about the security of external time servers but it is easy enough to make one of the local servers a master and act as a time server to the others.
    I have a small server that typically services some 30 or so external clients. I don't have any control over the clients and do not know anything about the setting of their system clocks. The clients send a time signal as part of a heartbeat and from this the server keeps track of the local time on each client and compensates for any difference when writing logs. I have seen this difference as big as 4 months but the compensation corrects it to within about a second. No adjustment of clocks is required for this.
    I still don't see this 'bug' as a serious bug. I just see a design problem to be solved without changing the OS time on any computer. I know this can be done since I do it. The only problem I see is if you want an accuracy of better than about 20 mS but that does not seem to be required for your system.
    Note - if Oracle accept your new bug report it could take years to fix even if lots of people vote for it to be fixed.

  • Which is better to use: BEx query or Web Application as an iView in portal?

    Hi gurus!
    Are there any experienced opinions, which is better - publish a BEx query in portal or publish a BEx Web Application in portal? Is it easier to alter the layout attributes etc. if I create a BEx Web Application first before publishing?
    What is the way of fixing for example filter item height if I publish BEx query in portal - is there a Web Application that it uses anyhow which I can fix? Or can I use in that case iView -properties in portal?
    Thankful for advice
    Sari

    ok, means i can use jsp:useBean tag for all my
    classes that are not actually bean. so it will be
    instantiated at run time and provide efficiency .No. Jsp:useBean is used for java bean components.
    >
    but when should i use import statement in my jsp and
    it happen at translation time so will it create any
    type of burden for my code if i import multiple
    classes.For non-java beans, you need to import the classes, period.
    It's not a burden, it's a necessity.

Maybe you are looking for

  • ORA-01152 error while creating db from custom template

    I have a database based on the "general purpose/transaction processing" db, but with a custom tablespace/data added. I have attempted to clone this database by using dbca to create a custom template (including data) from this database. The template c

  • WLan fails to connect after sleep mode - Satellite T110-10x

    Hi, Everything works fine, wireless connected. After sleep mode - it fails to connect although it detects my wireless network. I've tried the latest Realtek driver, still no good. I've verified that my setup is not to turn down wireless in the power

  • How to restore iPhoto and iBooks after clean install?

    I need to do a clean erase and reinstall of Yosemite.  How do I preserve my iPhoto and iBooks content and settings after reinstalling those apps? Thanks,

  • Clearing Line Items

    Hello Experts, We have created GL Account for Bank with only Line Item Management Activated and user has created the entries. Then user wants incoming and outgoing GL account with open item management. So, user reversed all the entries without taking

  • TS3623 Rented iTunes movie not loading.

    I have a new apple tv device. I rented a movie through iTunes however every time I go to watch it, I'm told there are xx number of minutes left to load. This number changes every time I check it but it is never fully loaded. The device is connected w