Concurrency with locks and wait/signal. Is it ok?

Hello,
I'm relatively new in concurrency. I've write this code that seems to work, but I'm not sure if there is any error (the concurrency concepts are not still clear for me).
In the following class "diskFile", I'll start 10 threads executing the class "diskCacheDataOneCall". The question is that the "populateCacheFromDisk" method should wait until 10 threads are finished and, if any thread produces an error, interrupt all threads and finish.
The code seems to work, but I have some questions like if I should synchronize the static variables Lock and Condition before using them.
Anyway, I'd like that an "expert" on concurrency tells me if this code is acceptable, or what kind of improvements can do (or, if there is some mistake, how to correct it).
I've spent many time reading tutorials about concurrency, and this is the result. Really, I'm not sure if I'm doing the things well, that's why I need the opinion of an expert in order to get better on concurrency.
Thanks in advance.
public class diskFile
// Static variables for threading.
public static Lock lock = null;
public static Condition cdFinished = null;
public static int numActiveThreads = 0;
public static Exception loadException = null;
// Main function
public static void populateCacheFromDisk() throws cacheServletException
ArrayList<Thread> arrThread = new ArrayList<Thread>();
// Init static variables.
lock      = new ReentrantLock();
cdFinished      = lock.newCondition();     
numActiveThreads = 0;
loadException = null;
try
// Iterate 10 times (for simplicity) ...
for (int i = 0; i < 10; i++)
// Create THREAD and store its reference
Thread thr = new Thread(new diskCacheDataOneCall());
thr.start();
arrThread.add(thr);
// Increment "numActiveThreads"
lock.lock();
numActiveThreads++;
lock.unlock();
// Her we wait while no error happens and still active threads
lock.lock();
while ( (loadException == null) && (numActiveThreads > 0) )
cdFinished.await();
// If an error happens in any thread, then interrupt every active thread.
if (loadException != null)
for (int i = 0; i < arrThread.size(); i++)
Thread thr = arrThread.get(i);
if (thr.isAlive()) thr.interrupt();
throw loadException;
catch (Exception e) { throw new cacheServletException(); }
finally { lock.unlock(); }
public class diskCacheDataOneCall implements Runnable
public diskCacheDataOneCall() {}     
public void run()
try
     diskFile.getCacheDataFromDiskOneCall(); // Load data from disk.
// Decrement "numActiveThreads"
     diskFile.lock.lock();
     diskFile.numActiveThreads--;
catch (Exception e)
diskFile.lock.lock();
diskFile.loadException = e;
finally
// Always signal and unlock.
diskFile.cdFinished.signal();
diskFile.lock.unlock();
}

Hello David,
Sorry but the code does not work. An IllegalMonitorStateException is throwed. Here I show you a simplified version (now with ThreadPoolExecutor):
   // Main class (it triggers "maxActive" threads)
   Lock lock  = new ReentrantLock();
   Condition cdFinished = lock.newCondition();       
   numActiveThreads = 0;
   loadException = null;
   try
    ExecutorService ex = Executors.newFixedThreadPool(numActiveThreads);
    for (int i = 0; i < numActiveThreads; i++) ex.execute(arrTasks.get(i));
    lock.lock();
    while ( (loadException == null) && (numActiveThreads > 0) )
               cdFinished.await();
    ex.shutdown();
   catch (Exception e) { throw e; }
   finally { lock.unlock(); }
  // Every thread.
  public void run()
   try
    doSomething();
    diskFile.lock.lock();
    diskFile.numActiveThreads--;
   catch (Exception e)
    diskFile.lock.lock();
    diskFile.loadException = cse;
   finally
    diskFile.cdFinished.signal();
    diskFile.lock.unlock();
  }The exception is:
// Fail in the "signal" (finally section)
Exception in thread "pool-1-thread-1" java.lang.IllegalMonitorStateException
at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.signal(AbstractQueuedSynchronizer.java:1666)
at com.vcfw.cache.cache.disk.diskCacheDataOneCall.run(diskCacheDataOneCall.java:44)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:650)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:675)
at java.lang.Thread.run(Thread.java:595)
// Fail in the "unlock" (finally section)
Exception in thread "pool-1-thread-2" java.lang.IllegalMonitorStateException
at java.util.concurrent.locks.ReentrantLock$Sync.tryRelease(ReentrantLock.java:125)
at java.util.concurrent.locks.AbstractQueuedSynchronizer.release(AbstractQueuedSynchronizer.java:1102)
at java.util.concurrent.locks.ReentrantLock.unlock(ReentrantLock.java:431)
at com.vcfw.cache.cache.disk.diskCacheDataOneCall.run(diskCacheDataOneCall.java:43)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:650)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:675)
at java.lang.Thread.run(Thread.java:595)
Some threads fail executing the signal, and some threads fail executing ythe unlock. An IllegalMonitorStateException seems to mean that the lock was not acquired by the thread, but I'm not able to see the mistake.
Can you help me?
Thanks.

Similar Messages

  • Lock and wait free data structures...???

    Hi - I am developing an application that requires multi-threading. We are testing this on CentOS 5, 64 BIT, running on Intel Quad Core machines, with 8 GB RAM (3 of them). I am using a III party tool to create a datagrid, and have 2 more machines in the federation to monitor performance.
    Java collections/synchronized collections has restriction on multithreading. If thread1 performs puts or removes objects in collection (Tree, Map, List, Set), thread2 cannot iterate. Thread2 can iterate only if it acquires synchronized lock on collection – this implies thread1 has to wait till iteration is over. This introduces latency. If without acquiring lock thread2 does iteration, then “concurrent modification thread exception” arises.
    For real time application like financial markets (multiple thread based application) every microsecond/millisecond matters.
    For workaround at present we have customized sun code by masking “modCount and expectedCount”. This means check for concurrent modification is disabled. But not quite sure this is correct approach. Other option was multiple buffering.
    Other option is lock and waits free data structures – which I am interested.
    Any ideas on this???
    cheers - Murali

    It depends on what is acceptable to you.
    If you are only iterating and not removing any objects through the iterator, then there are two concerns;
    1. Iterator skips some elements.
    2. Iterator iterates to non-existent elements causing NPE.
    You can also copy the datastructure. Then iterate over the copy.
    You can also do "copy on write." This causes a copy only when the datastructure is modified and those iterators already created are not affected. This is the technique I use.
    Eliminating locks is not the objective. Locking is very quick. Its the contention that you want to eliminate. COW can do this nicely in my experience. Depends on your requirements.
    P.S. Try assigning duke dollars to the question and you will probably get more viewers.

  • Risk with Locking and changinf password for SAPCPIC

    Hi All,
      Please advice if there is any risk with locking and changing password for SAP standard user SAPCPIC .We are on system 4.6D .
      Somewhere I could find that if there is any RFC destination defined with this user then it may cause problem after locking .I found following entry in RFCDES table .
    a       I                                          
    M=200,U=SAPCPIC,L=E,v=3FB20DF66CA32E419606388B51,   
    But I could not find any entry in sm59 for this .What is this entry as it is not there in SM59 .
    Any other known risks pls tell me .
    Thanks,
    Chittaranjan

    Can password of SAPCPIC user be changed without any problem?
    We are on ECC6.
    Report RSUSR003 refer to note 29276 and note says that changing password will cause problem with SM51 and some other report as the password is hard-coded there. Though this note seems to be bit old.
    Edited by: Pawan Kesari on Jun 9, 2009 7:58 PM

  • IMac with lock and password!

    I try to reset my administrator password because i couldn't remember the one I set up, then I follow the apple support steps to set it up, after I was done I restart my computer just like they suggested and now I have a freaking lock with password! I try few other steps and nothing is working, this is a refurbish iMac so no cd was enclosed in the box.  I believe the password was from the previews owner because all the codes I would normally use doesn't work..... I need to solve this problem from home the apple store is 2 hours away! I purchase this iMac thru the apple.com so you guys can see it's my property not stolen.

    You need to reinstall OS X:
    Reinstall Lion, Mountain Lion, or Mavericks without erasing drive
    Boot to the Recovery HD:
    Restart the computer and after the chime press and hold down the COMMAND and R keys until the menu screen appears. Alternatively, restart the computer and after the chime press and hold down the OPTION key until the boot manager screen appears. Select the Recovery HD and click on the downward pointing arrow button.
    Repair
    When the recovery menu appears select Disk Utility. After DU loads select your hard drive entry (mfgr.'s ID and drive size) from the the left side list.  In the DU status area you will see an entry for the S.M.A.R.T. status of the hard drive.  If it does not say "Verified" then the hard drive is failing or failed. (SMART status is not reported on external Firewire or USB drives.) If the drive is "Verified" then select your OS X volume from the list on the left (sub-entry below the drive entry,) click on the First Aid tab, then click on the Repair Disk button. If DU reports any errors that have been fixed, then re-run Repair Disk until no errors are reported. If no errors are reported then click on the Repair Permissions button. When the process is completed, then quit DU and return to the main menu.
    Reinstall Mountain Lion or Mavericks
    OS X Mavericks- Reinstall OS X
    OS X Mountain Lion- Reinstall OS X
    OS X Lion- Reinstall Mac OS X
         Note: You will need an active Internet connection. I suggest using Ethernet
                     if possible because it is three times faster than wireless.
    This assumes you had Lion or later installed. If the computer has Snow Leopard or earlier, then you will need the installer discs that should have come with the computer:
    Reinstall OS X without erasing the drive
    1. Repair the Hard Drive and Permissions
    Boot from your Snow Leopard Installer disc. After the installer loads select your language and click on the Continue button. When the menu bar appears select Disk Utility from the Utilities menu. After DU loads select your hard drive entry (mfgr.'s ID and drive size) from the the left side list.  In the DU status area you will see an entry for the S.M.A.R.T. status of the hard drive.  If it does not say "Verified" then the hard drive is failing or failed. (SMART status is not reported on external Firewire or USB drives.) If the drive is "Verified" then select your OS X volume from the list on the left (sub-entry below the drive entry,) click on the First Aid tab, then click on the Repair Disk button. If DU reports any errors that have been fixed, then re-run Repair Disk until no errors are reported. If no errors are reported click on the Repair Permissions button. Wait until the operation completes, then quit DU and return to the installer.
    If DU reports errors it cannot fix, then you will need Disk Warrior and/or Tech Tool Pro to repair the drive. If you don't have either of them or if neither of them can fix the drive, then you will need to reformat the drive and reinstall OS X.
    2. Reinstall Snow Leopard
    If the drive is OK then quit DU and return to the installer.  Proceed with reinstalling OS X.  Note that the Snow Leopard installer will not erase your drive or disturb your files.  After installing a fresh copy of OS X the installer will move your Home folder, third-party applications, support items, and network preferences into the newly installed system.
    Download and install Mac OS X 10.6.8 Update Combo v1.1.

  • Call JSP with applet and wait till it is loaded

    Hi,
    I am calling a JSP with a java-script. The targetpage needs some time, until the applet is loaded. I would like to call a function in the applet.
    My problem is, that I cannot set 'location.href' and straight after that call the applet, because it will not be there. How can I delay the applet-call, until it is really there?
    function loadOrder(){
    top.mainFrame.location.href = 'auftragseditor.jsp';
    top.mainFrame.OrderApplet.setOrder( orderno )
    I also fitted a while(...) loop between the two statements, but obviously the page is not build up in another thread. The loading will wait.
    Thanks for your help
    Klaus

    Assuming that top.mainFrame.OrderApplet.setOrder( orderno ) causes an exception because
    the applet is not loaded yet you should put it in a try and catch.
    One other problem is that orderno is not defigned anywhere in your method.
    function loadOrder(){
      top.mainFrame.location.href = 'auftragseditor.jsp';
      callApplet( orderno );
    function callApplet(strPassToApplet){
      try{
         top.mainFrame.OrderApplet.setOrder( orderno )
      }catch(e){
        // try again in .1 seconds
        setTimeout("callApplet(\"" + strPassToApplet + \");",100);
    }

  • PSE 8 organizer has photo with lock and message editor is busy

    I want to edit a picture from my gallery.  I click on fix and try to open full edit and I get message that the editor is busy.   There is one picture in my gallery that has a lock across it and states edit in progress.  I have exited and restarted PSE8 several times.  This message has been here for a whole day already.   How do I get to edit my photos again?

    Are you sure the editor isn't still running? The band with the lock means that you left a photo open in the editor when you switched back to the organizer, and the solution is usually just to close the photo in the editor. Try restarting your computer.
    The editor and the organizer are separate programs.

  • Found a bug on ios 7.0.2 with lock and home screen

    I have found a bug concerning the lock screen when you open the iphone and you push the screen to the rightt (sorry in french and dong know how to explain correctly)and at the moment you se the lck screen desapear you "take back" the lock screen page by pushing tp the left and then you will have the home page wallpaper on lock screen ( wont work if you have a passcode) and you can't have your default lock screen by putting the phone on sleep mode ... It just not coming back ..  You hve to put the iphone on sleep mode without toucching the screen to have your default wallpaper back on lock screen.. (Works on any iphone )
    I have another problem to with my batery since ios 7 update my battery goes 100-0% in like 5h .. And i just exchange my iphone because my power button was stuck and i dont have any garanty and its does that for all my friend with iphone 4s running ios 7.0.2
    Wish apple could fix those 2 bugs  or if anyone as any solution for me pleAse tell me
    Thank you.

    Apple Feedback

  • Txt received sound both with locked and unlocked phones.

    When I receive a txt my iPhone will make a sound with a locked screen, but when I unlock I hear the same sound again. Is there a way to turn off one of the sounds?

    Settings / Notifications / Messages
    Knock yourself out, oodles of adjustments to tweak on how you want the phone to let you know a message awaits.

  • Frozen iPod classic with lock and battery images on the screen

    When I unlocked my iPod classic while listening to music, everything stopped, and i got an image on the screen of the time when this happened (6:30), a lock image below it on the left, and a black horizontal battery on the right. The iPod won't work now, whether locked/unlocked or whether connected/unconnected to my PC/iTunes. What, if anything is the fix?

    Have you tried just a hard reset yet? To do this, first make sure the hold switch is toggled to the off position, then press and hold both the Select/Center and Menu buttons together long enough for the Apple logo to appear.
    B-rock

  • Problems with reconnecting and WIFI signal strength

    Three problmes
    1) Weaker signal strength
    2) Ipad doesn't connect to wifi after wake up
    2) apple.com takes forever to load. Shame.

    What kind of AP do you have? What is the FW Version? Is it the latest? What is your network configuration? If you are looking for help you may want to provide more information.

  • Carrier logo sometimes shows as 000-00 and loses signal

    Hiya,
    My girlfriends iphone 5 sometimes loses all signal and the carrier shows as 000-00 rather than EE. Regardless of signal in the area, the only way to get a signal back is to restart the phone!
    The phones not jailbroken or anything and is only about a month old. Its running the latest iOS.
    Any ideas?

    No I don't think its necessarily because of the 4G rollout.
    My iPhone5 has a Orange/EE 3G sim card and contract.
    This is what my theory is...
    My iPhone5 is set to automatically select the best network. It can see the 4G EE network is available, but when it connects via my 3G sim card it glitches / nullifies the signal and just reports that weird 000-00.
    Ever since I turned off 4G / LTE in settings I have not had the 000-00 error.
    So now it isn't getting confused with 4G and 3G signals, it doesn't give the error.
    So my theory is supported by my experience.
    Out of curiosity, is everyone who is having this problem absoloutely sure they have 4G sims??? I got my iPhone on release day, as a new contract, assumed it was 4G and only found out after a customer service phonecall much later that infact the new contract I had taken out was only a 3G one despite it being a brand new contract with an iPhone5 (yet that was one of the selling points by Orange / EE.)

  • InDesign CC concurrently on Win and Mac

    I run Parallels on my mac OS10 concurrently with Win7, and carry a Gateway Win8. 
    It sounds like CC is platform independent -
    could I access and edit my files from the Gateway and the Mac/Mac side and the Mac/Win side?
    I pay for the cloud app, and access from wherever?

    That's one of the biggest selling points to me. And it IS helpful.
    Bob

  • Grey screen with lock icon

    Macbook not booting properly, install disk nothing, press option on start up goes directly to grey screen with lock and login bar, tried all passwords and ...Nothing
    cannot safe boot. cannot reset PRAM. regular boot startup displays apple icon and spinning wheel.. Have no idea what may have caused issue (not the last one to use it) In other words HELP!

    I was able to do this ! YAY ! I believe I did something incorrectly on the first go with the PRAM reset. I was able to enter Single User Mode with original disk. Yay ! It was indeed the firmware password! Thank you Kappy !
    Following Kappy's steps, I did the following;
    If you're running OS 9, you may need another mac (though i suspect a PC with firewire and a HFS driver would do) and a firewire cable. You will need to delete preferences pertaining to keychain access and any keychains in the preferences folder in the system holder The first imacs ran this so its plausible
    If you're running OS X on the imac
    Single user mode would do the trick unless there's open firmware password protection in place
    To go into single user mode
    Press the power button to start the computer.
    Immediately press and hold the Command (Apple) key and one of the following: the "s" key for single-user mode. (Command-S) This should boot into a white screen, and iirc throw you into a command prompt
    These instructions should work for older versions such as 10.4. Khafshoh S' version works for newer systems 10.5 and better - 10.7 also has yet another option for resetting the password involving the 'resetpassword' command in lion recovery.
    Instructions for changing the password are based off of Apple's documentation though the documentation goes very in-depth.
    You would then mount the file system as writable with
    mount -uw /
    then find out what the accounts on the system are with
    ls /Users/
    then change their passwords with
    passwd username
    reboot and get back into graphical mode with
    reboot
    Then check the accounts to work out which one is the admin account.

  • Select and update with lock exclusive

    Hello Everybody
    In our application we have a table autonum     to handle unique keys for all other tables.
    In Autonum we have a column "SUCHBEGRIFF" char(40) unique KEY and a column "WERT" fixed(10,0).
    Suchbegriff has values like Rechnungsnr,Auftragsnr,Bestellnr ...
    Example:
    Befor inserting a record into table rechnungen we do:
    Select wert from autonun where suchbegriff = "Rechnungsnr" with lock exclusive.
    l_rechnrneu = wert + 1 
    update autonum set wert = ?l_rechnrneu where suchbegriff = "Rechnungsnr"
    commit
    (then l_rechnrneu is used for an insert into rechnungen command)
    This technic works for all tables (250) in our application.
    We have about 400 concurrent users working with maxdb 7.6 via odbc 7.6
    No problems since 2 years!
    Now we start some backgroundjobs from an xp-workstation.
    We have scheduled 5 jobs, starting every 5 minutes, same time.(Same user,same odbc-connection)
    Each job inserts records into a table joblogs and therefore needs a unique JOBLOGNR from autonum.
    Now we run into problems 2 or 3 times a day?
    <Sometimes the backgound jobs are running (waiting?) without inserting a record into joblogs (deadlock?)
    And more worse:
    Sometimes the insert into joblogs failes with "duplicate key" ??
    We don't know where to begin? Maxdb Problem ? Workstation problem?
    Any help welcomed
    Best regards
    Albert

    > >Gosh - that's information overloading at it's best...
    > We call this needed information.
    > What does our SAP-System? We have 1 mandt,60 accounting areas and about 200 werks!
    > Of course SAP uses internal unique keys for all tables, but we configured different "number intervals" for each werks.
    With "information overloading" I was referring to the multiple meanings you encode in just one column (your "rechnungs-no").
    SAP tables do not have this.
    As you wrote, there is "MANDT", "BUKRS", "WERKS" ... and the primary key is defined over all relevant columns.
    There is no primary key column where all the different meanings are concatenated together.
    So there aren't any surrogate keys here (a.k.a. AUTOID) used here - (ok except the infamous DDLOG sequence...).
    > >What do you do, when the value of an invoice has to be changed? Update the primary key of the table?
    > Update rechnungen set amount = xyz,...... where rechnungnr = nnn
    > We never change rechnungsnr,if the invoice was wrong we produce a credit for it and then write a new invoice
    So, you could use a sequence here instead as well.
    > > We don't use rollback when fetching logids from autonum.
    > >So what do you do, when connection fails, the database crashes or the client application hits an error?
    > >You use rollback. There is no way to avoid it.
    > >Your application gets a "duplicate key" error - the database performs a rollback of your last action. What does your application do then? Commit?
    > Sorry, i meant that we do not do rollbacks over  2 or 3 inserts or updates in different tables.
    > SQL-Command,On error = messagebox,errorlog,quit
    You don't handle the fetching of the new number in the same transaction as the actual insert of your application data in the same transaction?
    > >What isolation level do you use?
    > We use DATABASE ISOLATION LEVEL 0
    Hmm... did you read the documentation on SQL Locks?
    [Internals Course - SQL Locks|http://maxdb.sap.com/training/internals_7.6/locking_EN_76.pdf] :
    "Isolation level 0 does not offer any protection against access anomalies."
    Basically it might have happened that the same number is read twice.
    Perhaps the application is not always requiring locks when reading data from this table?
    > After connecting to the database via odbc we do
    > =SQLSETPROP(verbindungsnr,"Transactions",2)
    > 2 = Transaction processing is handled manually through SQLCOMMIT( ) and SQLROLLBACK( ). Read/write.
    > =SQLSETPROP(verbindungsnr,"DisconnectRollback",.T.)
    >
    >
    > So normal select commands are fired without a following commit.
    > Insert and update commands are fired with a following commit command.
    > Selects from autonum are fired with "look exclusive"
    Please be more detailed here.
    What is the exact sequence of actions here?
    1. Fetch number from number table and update number table.
    2. COMMIT
    3. Insert new application data with the just fetched number.
    4. COMMIT
    or
    1. Fetch number from number table and update number table.
    2. Insert new application data with the just fetched number.
    3. COMMIT
    And what does your application do with its data when a rollback occurs?
    Is it guaranteed that all variables are reset?
    > Nevertheless you dislike our design, do you think it would be better (quicker,safer...) to use an internal databases procedure to get
    > the next speaking number for a given "suchbegriff" from our autonum table? (no translation of the sql-command every time)
    No, currently we don't know what is causing the problem, so we cannot tell whether such a change would help. In fact, right now it would make things more complicated because we would less understand, what's happening here.
    Concerning your design: it's not about "liking" or "not liking it".
    I just pointed out some problems that result from the design as it is.
    > select   wert into :neuerwert FROM "BWPROGI"."AUTONUM"  WHERE upper(suchbegriff)     = upper(:suchkey) WITH LOCK EXCLUSIVE;
    > update  "BWPROGI"."AUTONUM" set wert = wert + 1 WHERE upper(suchbegriff)     = upper(:suchkey) ;
    > SET neuerwert = neuerwert + 1;
    > end;
    1. The WHERE clause UPPER(suchbegriff) = UPPER(...) is the best way to disable the efficient use of any index structure. Better make sure that your data is in the right format in the table when you enter it and then look it up without the UPPER() conversion. 
    2. I wouldn't perform the increment two times.
    Get the current value into your variable, increment this variable, set the current value in the table to the variable.
    > A char(10) return value would be nice and i don't know wether this would be the quicker way.
    Why should it? You would have to convert it first - that's additional work.
    Anyhow, to move ahead with your duplicate keys problem, you may perform a vtrace with the "stop on error" option.
    As your error is a duplicate key on a primary key constraint you should set "stop on error" to the error code "200".
    The next time your application hits the error, the vtrace automatically stops and we could examine what happened before.
    See [MaxDB database trace|https://wiki.sdn.sap.com/wiki/x/2yg] for details on how to activate the trace.
    When the error occurs next time and you caught it in the vtrace we can take a look at it.
    regards,
    Lars

  • Having a problem with threads and using locks

    I was hoping someone could give me some hits on getting my code to run properly. The problem I am having is I think my locks and unlocks are not working properly. Plus, for some reason I always get the same output, which is:
    Withdrawal Threads         Deposit Threads            Balance
    Thread 2 attempts $29 Withdrawal - Blocked - Insufficient Funds
    Thread 4 attempts $45 Withdrawal - Blocked - Insufficient Funds
    Thread 6 attempts $34 Withdrawal - Blocked - Insufficient Funds
    Thread 7 attempts $40 Withdrawal - Blocked - Insufficient Funds
                                    Thread 1 deposits $187          $187
                                    Thread 3 deposits $169          $356
                                    Thread 5 deposits $61           $417
    Press any key to continue...If someone can see the error I made and doesn't mind explaining it to me, so I can learn from it, I would appreciate that very much.
    /************Assign2_Main.java************/
    import java.util.concurrent.*;
    public class Assign2_Main
    {//start Assign2_Main
        public static void main(String[] args)
        {//start main
               // create ExecutorService to manage threads
               ExecutorService threadExecutor = Executors.newCachedThreadPool();
            Account account = new SynchronizedThreads();
            Deposit deposit1 = new Deposit(account, "Thread 1");
            Deposit deposit2 = new Deposit(account, "Thread 3");
            Deposit deposit3 = new Deposit(account, "Thread 5");
            Withdrawal withdrawal1 = new Withdrawal(account, "Thread 2");
            Withdrawal withdrawal2 = new Withdrawal(account, "Thread 4");
            Withdrawal withdrawal3 = new Withdrawal(account, "Thread 6");
            Withdrawal withdrawal4 = new Withdrawal(account, "Thread 7");
            System.out.println("Withdrawal Threads\t\tDeposit Threads\t\t\tBalance");
            System.out.println("------------------\t\t---------------\t\t\t-------\n");
            try
                threadExecutor.execute(withdrawal1);       
                threadExecutor.execute(deposit1);     
                threadExecutor.execute(withdrawal2);  
                threadExecutor.execute(deposit2);    
                threadExecutor.execute(withdrawal3);
                threadExecutor.execute(deposit3);       
                threadExecutor.execute(withdrawal4);
            catch ( Exception e )
                 e.printStackTrace();
                //shutdown worker threads
               threadExecutor.shutdown();
        }//end main
    }//end Assign2_Main/******************Withdrawal.java****************************/
    public class Withdrawal implements Runnable
    {//start  class Withdrawal
          *constructor
        public Withdrawal(Account money, String n)
             account = money;
             name = n;
        public void run()
        {//start ruin
             int newNum = 0;
                newNum = account.getBalance(name); 
               Thread.yield();
        }//end run
        private Account account;
        private String name;
    }//end  class Withdrawal/*******************Deposit.java***************/
    import java.util.Random;
    public class Deposit implements Runnable
    {//start class Deposit
          *constructor
        public Deposit(Account money, String n)
             account = money;
             name = n;
        public void run()
        {//start run
                try
                     Thread.sleep(100);
                   account.setBalance(random.nextInt(200), name);
                }// end try
                catch (InterruptedException e)
                  e.printStackTrace();
       }//end run
       private Account account;
       private Random random = new Random();
       private String name;
    }//end class Deposit/********************Account.java*****************/
    *Account interface specifies methods called by Producer and Consumer.
    public interface Account
         //place sum into Account
         public void setBalance(int sum, String name);
         //return  value of Account
            public int getBalance(String name);         
    } /**************SynchronizedThreads.java****************/
    import java.util.concurrent.locks.*;
    import java.util.Random;
    public class SynchronizedThreads implements Account
    {//start SynchronizedThreads
          *place money into buffer
        public void setBalance(int amount, String name)
        {//start setBalance
             // lock object
             myLock.lock();           
            sum += amount;
            System.out.println("\t\t\t\t" + name + " deposits $" + amount +"\t\t$"+ sum+"\n");       
               //threads are singnaled to wakeup
            MakeWD.signalAll();
              // unlock object                                                
            myLock.unlock();
           }//end setBalance
            *gets the balance from buffer
           public int getBalance(String name)
        {//start getBalance
             int NewSum = random.nextInt(50);
             //lock object
            myLock.lock();
            try
                 if(sum > NewSum)
                     //takes NewSum away from the account
                     sum -= NewSum;
                        System.out.println(name + " withdraws $" + NewSum +"\t\t\t\t\t\t$"+ sum+"\n");
                else
                     System.out.println(name +  " attempts $" + NewSum + " Withdrawal - Blocked - Insufficient Funds\n");                 
                     //not enough funds so thread waits
                        MakeWD.await();         
                //threads are singnaled to wakeup
                MakeD.signalAll();     
                }//end try
            catch (InterruptedException e)
                   e.printStackTrace();
            finally
                 //unlock object
                 myLock.unlock();
            return NewSum;     
         }//end getBalance
         private Random random = new Random();  
         private Lock myLock = new ReentrantLock();
         private Condition MakeD = myLock.newCondition();
         private Condition MakeWD = myLock.newCondition();
         private int sum = 0;
    }//end SynchronizedThreads

    You can also try to provide a greater Priority to your player thread so that it gains the CPU time when ever it needs it and don't harm the playback.
    However a loop in a Thread and that to an infinite loop is one kind of very bad programming, 'cuz the loop eats up most of your CPU time which in turn adds up more delays of the execution of other tasks (just as in your case it is the playback). By witting codes bit efficiently and planning out the architectural execution flow of the app before start writing the code helps solve these kind of issues.
    You can go through [this simple tutorial|http://oreilly.com/catalog/expjava/excerpt/index.html] about Basics of Java and Threads to know more about threads.
    Regds,
    SD
    N.B. And yes there are more articles and tutorials available but much of them targets the Java SE / EE, but if you want to read them here is [another great one straight from SUN|http://java.sun.com/docs/books/tutorial/essential/concurrency/index.html] .
    Edited by: find_suvro@SDN on 7 Nov, 2008 12:00 PM

Maybe you are looking for

  • I would like to open attachments without saving them. Is there a way to do that in Firefox like in IE ?

    It is nice to open an attachment without saving it to a specific location. I am used to doing this with Internet Explorer. However, it does not seem that I can do that with Firefox. Is that true or am I missing something ?

  • Glitch with playlist used for photos slideshow

    Here is another interesting one - don't know whether people have noticed... I have a mixture of smart and normal playlists. They appear on the nano in alphabetical order, unlike iTunes where he smart ones are always above the normal ones. I say this

  • CS3 Has Stopped Working and Won't Reinstall - HELP I can't Work!

    Hi, I have CS3 running on a Windows Vista 32 bit PC with 4 gig of RAM, dual core processor. The other day I went to use Photoshop and got the message that the product had stopped working. This turned out to be the case with all of the apps. The solut

  • XP Mode in Windows 8

    Hi, Is it legal to have XP mode in Windows 8? What I mean is, I use Hyper-V in Windows 8 and import vhd file in XP mode after I extract it from XP Mode Installer. Then I have Windows XP in Hyper-V.

  • Change server time

    Hi to all, I have 10.2g database on a Windows Server 2003 in production. What would be the impact on the database if I change server time i.e. if I roll the clock backwards? My database server takes time from my DC server and I wont to roll the clock