Thread Contention

I've written a producer/consumer type of application. the producer receives data input (speed and time) over a serial connection and places it in a queue of sorts, set up much like the examples at Sun. The consumer picks up the values, calculates a speed and moves an animation object across a display.
I've put both the consumer and producer programs in their own threads. the driver program starts the producer program in its thread and calls an openConnection method to open a serial connection. I then call a startCollecting method that begins reading serial input. The input is dumped in the queue, which has a capacity of 5 values. If the producer fills all five values, it goes into a wait state. the consumer is supposed to pick up the values, freeing the producer to place more values in the queue. My problem is once the producer goes into its wait state, everything freezes, including the driver program interface, and the visual display the consumer is running in.
If I do not call the openConnection and startCollecting separately, but rather just start the producer thread and let it open a connection and start collecting automatically all runs well. It seems the problem exist whenever I attempt to access methods inside the threaded program.
Any help would be greatly appreciated. Have not found any really examples of how to resolve this approach.

I've put both the consumer and producer programs in
their own threads.good.
the driver program starts the
producer program in its thread and calls an
openConnection method to open a serial connection. I
then call a startCollecting method that begins reading
serial input. The input is dumped in the queue, which
has a capacity of 5 values. If the producer fills all
five values, it goes into a wait state. the consumer
is supposed to pick up the values, freeing the
producer to place more values in the queue. My problem
is once the producer goes into its wait state,
everything freezes, including the driver program
interface, and the visual display the consumer is
running in. this sounds like you possibly missed something in the area of thread synchronization. did you invoke notifyAll() after you put somthing in the queue?
the typical queue implementation looks like this:
package farmerworker;
import java.util.*;
* A thread safe queue used to synchronize farmers and workers. Farmers put
* objects into the queue and workers retrieve them. Workers may arbitrarily
* invoke {@link #dequeue()}. Their thread blocks until an instance can be
* retrieved from the queue or the thread is interrupted. <p>
* technically {@link #enqueue( Object )} and {@link #dequeue()} are
* synchronized using {@link #wait()} and {@ #notify()}.
* @author    klemme
* @created   24. September 2001
* @version   $Revision$
public class Queue {
     * Checks whether there are objects in the queue.
     * @return   'true' if there are instances in the queue. WARNING: in a
     *      multithreaded environment it is only reasonable to invoke this
     *      method when holding a lock on this instance, i.e. in a <code>synchronized</code>
     *      block.
    public boolean isEmpty() {
        synchronized ( lock ) {
            return queue.isEmpty();
     * Return the number of objects currently in the queue.
     * @return   a value >= 0
    public int size() {
        synchronized ( lock ) {
            return queue.size();
     * Put an object into the queue.
     * @param obj  the instance to enque
    public void enqueue( Object obj ) {
        synchronized ( lock ) {
            queue.add( obj );
            lock.notify();
     * Retrieve something from the queue. This method blocks until either an
     * Object can be retrieved from the queue or this thread is interrupted.
     * @return                          the next Object in the queue
     * @exception InterruptedException  in case of premature termination of this
     *      thread.
    public Object dequeue()
        throws InterruptedException {
        synchronized ( lock ) {
            while ( isEmpty() ) {
                lock.wait();
            return queue.remove( 0 );
    private List queue = new LinkedList();
     * The lock on which this instance synchronizes.
    protected final Object lock = queue;
[/code}]instead of synchronizing on "lock" you can just synchronize methods.  then you have to invoke notifyAll() and wait() on "this".  you can also change the conditions when the queue accepts new input.  this Queue is unbounded, but you can implement a size limit via a condition testing for the size in enqueue(). (typically this is easier done then working with a ring buffer in a fixed sized array, since then you need two indexes etc. and the overhead of a LinkedList is not too big. - btw: LinkedList is faster than ArrayList if you don't need indexed access like in this case.)
regards
robert

Similar Messages

  • Thread Contention Issue , Help !

    public class vipThread implements Runnable
    private static volatile boolean lockMe=false;
    public synchronized static boolean getLock ()
         return lockMe;
    public synchronized static void setLock (boolean lock)
         lockMe = lock;
    public void run ()
    synchronized(this)
                   if(!this.getLock ()) {
                   this.setLock(true);
                   ret = vipRequestProcessor.getNewRequests ();                         
                   this.setLock(false);
    getNewRequests is not a synchronized method. Do i need to have it synchronized ? i do have a thread contention issue here. Couple of threds pickup the same request fromt he database.
    Help appreciated
    thanks
    pras

    public class vipThread implements Runnable
    private static volatile boolean lockMe=false;
    public synchronized static boolean getLock ()
    return lockMe;
    public synchronized static void setLock (boolean
    an lock)
    lockMe = lock;
    public void run ()
    synchronized(this)
    if(!this.getLock ()) {
    this.setLock(true);
    ret = vipRequestProcessor.getNewRequests ();
    this.setLock(false);
    getNewRequests is not a synchronized method. Do i need
    to have it synchronized ? i do have a thread
    contention issue here. Couple of threds pickup the
    same request fromt he database.
    Help appreciated
    thanks
    prasIf the "getNewRequests() method is only called from your vipThread, then you don't have thread contention problem.

  • Checking for New Thread Content

    Other than "subscribing" to a thread, is there an efficient way to figure out whether there's any new content for any of the threads in "My Posts"? As my number of posts increases, it's taking longer and longer to scan that list for updated content.
    Thanks for any suggestions.

    Tuttle wrote:
    I was hoping for something like a page with "My Updated Posts". I guess there isn't one.
    There isn't. Have you tried loading My Posts pages that are populated with more than the standard 10 posts, e.g.,
    http://discussions.apple.com/myposts.jspa?start=0&range=100
    which will load your last 100 posts? (You can insert any number after range= .)
    Thanks for the suggestion.

  • Receiver File content conversion - NO Output

    Hi, yesterday i posted already to this topic but i chose to make a new thread.
    I have an IDoc2File Scenario where i put the generated File to the filesystem of the XI-Server.
    I try to do a file content conversion at the receiver side. I already read several blogs and also the official documentation (which is kind of bad - because the arne't posted all supported parameters which could be used on the recordset)
    But anyway, the is a txt file written but without any details inside, no data is deliverd.
    I do a message mapping and try to put only some data to the end-file.
    here is my MT which i try to convert:
    MT_Tafel
    ++TafelRecordset
    +++TafelDetailsStructure
    ++++TAFIST
    ++++TAFSOLL
    My parameters at the receiver communication channel are:
    Recordset: TafelDetailsStructure
    TafelDetailsStructure.endSeparator = 'nl'
    TafelDetailsStructure.addHeader = 0
    TafelDetailsStructure.fieldSeparator = ,
    I have the right message protocol, i am trying to write a simple text file, i have no file-coding like ASCII, file is directly written into an empty one - and that's all.
    The file is written but without data inside.
    Do i have to announce the filednames i want to write? Like TafelDetailsStructure.fieldNames??
    Do i have to add Parameters concerning the tags on the higher level, like TafelRecordset?
    Is there a general overview about all parameters you can use on this file content conversion?
    Can anybody help me with my scenario - i have no clue what i have done wrong. Communcation channel says everthing is fine, message succesfully transfered.
    best regards, Jens

    hi,
    you need to mention the names of the field by
    TafelDetailsStructure.fieldNames where u need to specify the filed names.
    and also chk the similar thread
    content conversion
    plsz check the blog
    /people/arpit.seth/blog/2005/06/02/file-receiver-with-content-conversion
    check this like below,
    http://help.sap.com/saphelp_nw04/helpdata/en/d2/bab440c97f3716e10000000a155106/content.htm
    hope this helps,
    kvr
    Message was edited by:
            PrasadBabu Koribilli

  • Restore old iMessage chat contents after OS X reinstall?

    Last night I had to do a wipe of my MacBook Pro running Mountain Lion. At the end of the installer I chose to migrate all my old apps/data/settings back onto the machine from a recent Time Machine backup. Everything transferred over correctly with the exception of all  my iMessage threads. When you open the Messages app, all the recently chatted with friends show up on the left hand sidebar, but when you click on one, the thread contents are blank. Is there any way to manually reimport all of the old iMessage chat contents into my currently installation?
    I still have all of my old iMessage data on my Time Machine backup under the folder "~/Library/Messages" folder. I tried copying over the new version of this folder with the old version stored on the Time Machine backup, but the reimport didn't seem to take so I reverted back.
    Anyone have any ideas? Thanks

    HI,
    I would have said that the ~/Library/Messages folder was the thing to copy back.
    As you "owned" the original I would have thought there would be no Ownership  issues.
    You would need the Archive folder (All Old Chats if you were saving them) and the Chat.db items as these hold the iMessages chats and the attachments if there are any.
    Two possible issues
    Creating an iCloud ID with an older Apple ID and using a different name in Messages to register for iMessages
    Although iCloud web site will let you login with either the originating Apple ID or the created @me.com name iMessages registers only one of these rather than the "whole Account".  (Obviously one can become an alias in Messages for the iMessages account)
    The second is related as it is which ID is then used to Login in System Preferences > iCloud.
    This then passes over to Mail, Contacts and Calendars and can be active for Messages.
    9:26 PM      Saturday; October 13, 2012
    Please, if posting Logs, do not post any Log info after the line "Binary Images for iChat"
      iMac 2.5Ghz 5i 2011 (Mountain Lion 10.8.2)
     G4/1GhzDual MDD (Leopard 10.5.8)
     MacBookPro 2Gb (Snow Leopard 10.6.8)
     Mac OS X (10.6.8),
     Couple of iPhones and an iPad
    "Limit the Logs to the Bits above Binary Images."  No, Seriously

  • There used to be an option in this forum to subscribe to threads

    There used to be an option in this forum to subscribe to threads, where is it nowadays?
    <Re-Titled By Host>

    You could choose to look into 'Following' within the thread you wanted see updates in,
    and be sure to look into your Profile choices on email updates on thread content, if you
    want to see any activity and have it appear in your inbox. (I do not use this email item.)
    Also there is a set of icons in the top right section of an open thread where options appear.
    If you are the author of a topic, some of these icons (the gear) will allow other choices but
    they may change after a time; one of these may be an edit option that fades out shortly.
    In your choice of section to view, as seen from your access when logged in to this site,
    you can see a menu to the left of the displayed post topics, and click on that to view
    any that may appear. For some to be populated by any content, you will have had to
    have done some action to cause it. For example, if you never wrote a question, that
    area "authored" would be empty.
    There is a section on how to use these Apple Support Communities (discussions) with
    a link to information at the start of this part of the Apple web site...
    New to the community? Start here.
    {also information about this topic}
    •Apple Support Communities Terms of Use
    Such questions also may be addressed to an ASC area about those topics.
    Using Apple Support Communities
    Hopefully this helps somewhat.
    Good luck & happy computing!

  • Too many threads?

    Is there a such thing as using too many threads? I'm in the planning stages and it would be nice to have each object running on its own thread, but is this a horrible thing? Is there a general rule of thumb on the number of running threads?

    Personally, I think if you have more than 20 or so
    threads in a process, the task swiching time will
    start to exceed the useful work done. Its better to
    use one of the standard patterns for pooling threads.There is no one 'right' or 'maximum' number of threads.
    The number of threads after which things get overly inefficient varies greatly depending on the characteristics of the application. If 20 threads fully consume the CPU, then adding more threads will only make things worse. If 20 threads can only use 10% of the CPU resources because of external delays (network access, database, etc.) then it may be true that using 200 threads is best, assuming of course that the throughput capacity of the network, database or external system can accomidate the increased load.
    What you'd like to avoid is preemption - a runnable thread interrupts a currently running thread that still has need of the CPU - this wastes time. If the running threads tend to block before the end of their time slice, then there really isn't going to be any added cost to context switches, nothing else would be using the CPU anyway.
    If the computer the application is running on has a number of CPU's, then it can probably accomidate more threads than a single CPU system. Of course there are limits to the effectiveness of this and a single process with many threads may not (often does not) run as efectively as several copies of the application with fewer threads each due to various inter thread contention issues.
    Chuck

  • SAP third party Pre-delivered SLD Content - Product and SWCVs

    Hi All,
    I have started this thread on LinkedIn and I wanted it to be viewed by all of you for your valuable suggestions and thus from SAP too... The thread is [here|http://www.linkedin.com/groupAnswers? viewQuestionAndAnswers=&discussionID=20482912&gid=81282&commentID=16700717&trk=view_disc ]
    VJ
    Edited by: VijayaShankar Konam on May 22, 2010 12:12 PM

    Here is the thread content until now -
    Hi All,
    I have been working on integration of our product with SAP. We wanted our SLD objects for the product and the swcs to be delivered as part of SAP's pre-delivered SLD content, so that the client could simply import our design objects in to their PI landscape (Similar to how SAP provides PI content on service market place. We do have partnership with SAP and this product integration was not yet certified by SAP. However, they SAP agreed to supply our product and SWCs as part of the standard SAP CIM modal content).
    How ever, even when we gave our SLD export to SAP, when the latest CIM modal for SLD from SAP got released, we were surprised to see that, our product and SWCvs are created with the vendor name "sap.com". This absolutely makes our product and swcvs unusable as we would not be able to look at them in the SPROXY on application systems. This was the same case with an older client that I worked with too..!! Any one had similar experience with this? Shouldn't SAP
    be creating them with vendor as "<vendor>.com"? At least, our product is not owned by SAP..!!
    We all know that, if sap.com is the vendor for SLD objects, only SAP could provide the proxy implementations through an SAP support pack.
    Could someone from SAP PI Techies understand my point and care to respond?
    Regards,
    VJ

  • Custom name for Timer thread?

    Thread has the usefull setName() method to set a custom name for a Thread. Timer doesn't have such a method but a Timer is itself a Thread. How can I set a custom name for a Timer thread?

    Yes, very usefull for debugging, e.g. when running mutliple threads in an IDE, you can easily identify the thread to continue to inspect without inspecting the threads content/attributes.
    But also for logging: for a multithreaded server application having a log file, each thread can log messages to the log file (standard Java logging API). To be able to assign the messages to each thread, the thread name can be used as the message prefix.

  • Session pooling and statement handles

    Hi there,
    I have a large multi-threaded application (perhaps >100 threads). Each thread is continuously processing events (very high volumes) which involves some manipulation and some database operations (from a fixed set of possible operations).
    I am using session pooling but what I want to know is, Should I:
    (a) Prepare my fixed set of statement handles up front at program start-up when I'm creating the session pool and then reuse the statement handles in each event processing thread (also, is this thread safe ? even if it is, all threads would be contending on the same statement handles)
    or
    (b) Prepare the statement handle for each event which presumably will exploit the statement cache on the session pool. This would also mean not having statement handles shared between threads thus removing any thread contention issues.
    I think (b) is the option for me, but does anyone have any thoughts ?

    With a), one would think it's OK, but I would hate to find out that it's not thread safe by accident.
    But anyway, with b) the cost of allocating private statement handles in each thread seems very low. The memory required for the statement handle plus its bind and define handles could very well be below 8k per statement. If you've got say, 5 statements * 100 threads, you're only looking at around 4MB overall.
    Finally, you might want to make sure that the session pool statement cache is working by checking the values for 'executions' and 'parse_calls' in V$SQL for your statements.

  • Problems with WLS 4.5.1 and F5 Big IP HA+ Switch

    Hello. We're having problems with our F5 Big IP HA+ switch and pool of WLS
              4.5.1 servers (two in the pool currently). At seemly random intervals the
              Big IP believes the one or both of the servers are not responding, so they
              are removed from the pool. We have a growing body of anecdotal evidence to
              suggest that the servers are actually on-line and available during the
              event. Either the switch is confused or the WLS servers aren't always
              responding correctly to the HTTP requests sent by the switch for polling.
              We're having problems catching the problem with the right diagnostics.
              Has anyone out there observed similar behavior with these components?
              Thanks.
              - Sean McRae
              

    Sort of,
              I use iplanet between the 2, so I havent had this problem, but I have had
              several problems with clustering, here is what I recomend doing:
              write a simple java program (or whatever your prefered language) to do a HTTP
              ping on your distinct weblogic servers every X seconds/minutes where X is less
              than Big IPs death tolerance. Time how long/or if ever each of your pings take.
              turn on verbose gc.
              My guess is its one of 3 things:
              1.) your have a big gc going on and your server isnt responding quick enough
              and big ip is marking it dead
              2.) you have thread contention that is causing your server not to respond quick
              enough
              3.) your network has some issues and the packets arent making it there, or not
              quick enough.
              the ping program will prove/disprove #2 and lead you to or away from 3. Verbose
              gc will prove/disprove #1.
              hope this helps
              -Joel
              Sean wrote:
              > Hello. We're having problems with our F5 Big IP HA+ switch and pool of WLS
              > 4.5.1 servers (two in the pool currently). At seemly random intervals the
              > Big IP believes the one or both of the servers are not responding, so they
              > are removed from the pool. We have a growing body of anecdotal evidence to
              > suggest that the servers are actually on-line and available during the
              > event. Either the switch is confused or the WLS servers aren't always
              > responding correctly to the HTTP requests sent by the switch for polling.
              > We're having problems catching the problem with the right diagnostics.
              >
              > Has anyone out there observed similar behavior with these components?
              >
              > Thanks.
              >
              > - Sean McRae
              

  • How do I convert a StringReader to an InputStream?

    Hi:
    I have a String, and I need an InputStream - how do I create a stream from a string? My first idea (which may be wrong) is to create a StringReader.
    Thanks, Erik

    InputStream is = new ByteArrayInputStream("your string".getBytes("your desired character encoding"));The big question is - what character encoding do you desire? You can get the platform default encoding by using -
    InputStream is = new ByteArrayInputStream("your string".getBytes());but this frequently is not what is required. If you don't really care then you can cover just about everything with "utf-8".
    P.S. Your thread title and your thread content do not really match!

  • Cannot move the pages from one document to another

    Hi,
    I cannot move the pages from one document to another, abobe gets crashed. I am not sure but I think this was happening when I try to copy or move the threaded content. How to resolve this, this is happening in both CS4 and CS5. Can anyone help me?

    Thanks for ur reply.
    1. Open two documents, for ex doc1 and doc2, doc1 contais 4 pages, doc2 contains 2 pages
    2. Using Move Pages from the Pages panel menu in doc1, moving 1st two pages to doc2
    Move Pages  : 1-2
    Destination   : After page 1
    Move to        : doc2
    Actually I was not able to copy the textframe which is linked with another, immediately it crashes.

  • QI material cannot be make MB1A

    Hello,
    I have a material in Quality Management Tab of it, inspection set up was tick and maintain. Insp.Type: 08 (Stock transfer inspection) was active. and it has a stock of 2800 pc in MMBE in Quality Inspection. we want to scrap this stock, we made MB1A movement 553 on this one, i have an error message doing this (Change the Inspection stock of material 11111 in QM only) how could we make this to process and make the stock be SCRAP.
    Thank you so much,
    Ryan

    Hi Ryan,
    Clear me these.
    Is there any lot?
    Yes, then what is the status of that lot. (check as I have prescribed earlier.
    What is the status of your stock right now?
    You have tried QA32 is good thing.
    Forum: Product Lifecycle Management (PLM)
    There is tittle available for each forum. (At the Top of thread list)
    Under these titles the applicability criteria for the forum is written.
    E.g. for PLM.
    Questions regarding Product Lifecycle Management development and implementation are discussed here. Industry specific questions are welcomed too.
    For PP.
    Supply Chain Management - Production Planning Forum (not including APO)
    Now the question you have asked is applicable to QM, which is included under PLM in SAP. And generally the QM experts surfs at PLM forum. So whenever the moderator find that the posted thread can get better / faster / brighter response to the other forum, after considering the applicability criteria of the threads content, they migrates the thread to the right forum> (just as this one is shifted from PP to PLM)
    Regards,
    Shyamal.

  • Performance of UDP Receiver during high load

    Hello All,
    I have the following problem and hopefully somebody can help me with this.
    Our Application, SIP Proxy, is multi-threaded and this is the way we run it.
    We have a UDPReceiver Thread that listens on a particular port. We have a ThreadPoolManager that has 50 Worker threads that are started when the SIP Proxy is brought up. These threads follow the wait-notify mechanism. When we get a packet ( in UDPReceiver),we add the packet to a Vector and notify the threads ( not notifyAll). The thread that is notified picks up the first job in the vector. If there are no jobs in the vectors, the workers all wait on the synchronized object.
    So far no issues. Everything works fine when there is reasonable load. But when I reach a certain load I see UDP packets getting dropped (netstat -s -v 1 | grep udpInOverflows in T2000). The CPU utilization at this point is only 40%.)
    I face the same packet drop issue in Linux as well. I analyzed the problem and this is what I found out.
    Sometimes all the Workers are busy and UDP Receiver adds the jobs to the Vectors and there atleast 300 of these jobs in the queue ( Normally this would be 1 or 2). So when the Workers finish their existing job, they take the next one if there is any. Since there are 300+ jobs, the Workers (50 of them) pick their job. This is continuous till all the jobs in the queue are complete. Now I believe the UDP Receiver thread is not getting a chance to execute during this time
    and hence the UDP buffer overflows and we get packet drops ( I have done all the OS tuning to increase the receive buffer etc).
    I set a higher priority to the UDP Receiver Thread but still the same thing happened).. What is really puzzling me, how come this
    thread is starved for CPU if it shows as only 40% in prstat?
    Have any of you faced similar problems and if so how did you fix it?
    I can paste code snippets if need be.
    Thanks in advance
    Gokul

    We do have a similar setup to this. I think I would
    try to determine what the best case max throughput
    you can handle, by disconnecting the receiver from
    the queuing and worker thread machinery and just let
    it count how many packets it can copy into a buffer
    and throw out. This will allow you to get a better
    idea of what effect thread contention is having on
    your setup.Hi,
    Thanks for the quick response. I had done what you have suggested when I was trying out different combinations. The number of workers are something we have a control over at runtime and to ensure that there are no jobs being processed I set the Worker Count at '0'. This correlates to your suggestion. When I do this, there are no packet drops at even very high packet rate. ( Ofcourse the Vector keeps growing since there are no Workers to process it) and eventually I ran out of Memory.
    So as far as I can see our UDP Receiver is Ok. So it basically comes down to how do I make sure that UDP Receiver always get top priority?
    Have you faced this problem at all or is there is a threshold where you see this problem?
    Thanks again
    Gokul

Maybe you are looking for

  • ITunes 9.1 no longer synching iPhone Contacts to Mac Address Book

    Since installing iTunes 9.1 (79) today. my iPhone will no longer synch to the Mac Address Book. iPhone software 3.1.3, Mac OS 10.6.3 MacBook Pro 3.1. The only thing I can think of is that my iTunes library is on an external drive (not with me). Every

  • Loading a Previously Saved Task into LabView

    I have created a digital generation task in LabView and saved it using DAQmx Save Task.vi. I am able to open and run my task in Measurement and Automation Explorer. Now I am wondering if it is possible to load this task back into LabView and run it i

  • Exception message changed

    We noticed that when an EJB in WL7 throws an exception with a message, the client sees a differente message, enriched with the server side exception trace. So if you client uses the message to get information from the server, this message is useless.

  • PSE 11 Keeps Crashing

    Hi everyone, Hope someone can point me in the right direction here. Every time I open Editor in PSE11 it crashes within minutes. Sometimes it allows me to open a picture before crashing, other times it happens before I get a chance. I have tried unin

  • DashBoard error: 404 - not found

    Dear Friends, I was trying to Set up the Dashboard in My System. Have done all the necessary steps as Instructed by SAP. Have assigned all the necessary licenses to the B1i user. Have Restarted all the required Services. But I am getting the followin