Thread producer/multiple consumer example!!

Hi,
does anybody have an example of a procucer/multiple consumers thread
example.
I would like to do the following:
-start one producer thread that writes data into an object.
-start more consumer threads that read and process that data
from that object.
Conditions:
-data put on the object should only be handled by one consumer!!
(so if the data would be numbers: 1, 2, 3 than number 1 should
be fetched by one consumer and the other consumers don't see it
anymore!).
If anybody has an example for this, please let me know!
Thanks,
Sven

Check out Doug Lea's work
http://g.cs.oswego.edu
and the book
http://java.sun.com/docs/books/cp/
util.concurrent is a great package. It is utilized by many many big java projects. There is a producer consumer example in the book, using util.concurrent classes.
-Spinoza

Similar Messages

  • Thread Producer and Consumer

    Hi
    I have an array that keeps Integer into it. what is wrong with this problem i cant fix it. Thread Consumer never start.
    Producer class: Putting nr 1 to 50 int into array eg. 1-2-3-4-5-6-7-8-9-10.....
    Consumer class : removing 50 down to nr 10 from array 50-49-48-47...
    Main Class : Threads creator and starter.
    How can i let Thread P start before C. and when P is finnish it call C, and then C when its done it wakes up P and running like that for life. HOWWW Plz help
    MAIN CLASS:
    import java.util.ArrayList;
    public class Main {
    static ArrayList<Integer> list = new ArrayList<>();
    public static void main(String[] args) {
    Thread p = new Thread(new Producer());
    Thread c = new Thread(new Consumer());
    p.start();
    c.start();
    PRODUCER CLASS:
    public class Producer extends Main implements Runnable{
    @Override
    public void run() {
    while (true) {
    // Tilføjer cornflakes til arrayListen hvis < 10
    if (list.size() <= 10) {
    for (int i = list.size(); i < 50; i++) {
    list.add(i);
    System.out.println("p : " + list.size());
    try {
    Thread.sleep(100);
    } catch (InterruptedException ex) {
    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    }// end Forloop
    }// end if
    }// end while
    Consumer CLASS
    public class Consumer extends Main implements Runnable {
    @Override
    public synchronized void run() {
    while (true) {
    // Tilføjer cornflakes til arrayListen hvis < 10
    for (int i = list.size(); i > 10; i--) {
    list.remove(i);
    System.out.println("c : " + i);
    try {
    Thread.sleep(100);
    } catch (InterruptedException ex) {
    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    }// end Forloop
    }// end while
    }

    That's a reason for failure in general by the way - trying to do stuff without understanding stuff. Its best avoided in the future - first learn and learn well, then code. Then when you have problem with said code, come here and ask for help. Not before that, a forum is not a personal information service or substitute teacher.

  • Old Producer/Consumer Example question

    how would I take this code, the old producer/consumer example, and make it for 2 consumers and 1 producer?
    basically, like this:
    Producer put 1
    Consumer #1 got 1
    Consumer #2 got 1
    Producer put 2
    Consumer #1 got 2
    Consumer #2 got 2
    etc.....
    ***********Producer.java***************
    public class Producer extends Thread {
    private CubbyHole cubbyhole;
    private int number;
    public Producer(CubbyHole c, int number) {
    cubbyhole = c;
    this.number = number;
    public void run() {
    for (int i = 0; i < 10; i++) {
    cubbyhole.put(i);
    System.out.println("Producer #" + this.number
    + " put: " + i);
    try {
    sleep((int)(Math.random() * 100));
    } catch (InterruptedException e) { }
    ***********Consumer.java***********
    public class Consumer extends Thread {
    private CubbyHole cubbyhole;
    private int number;
    public Consumer(CubbyHole c, int number) {
    cubbyhole = c;
    this.number = number;
    public void run() {
    int value = 0;
    for (int i = 0; i < 10; i++) {
    value = cubbyhole.get();
    System.out.println("Consumer #" + this.number
    + " got: " + value);
    ***********CubbyHole.java***********
    public class CubbyHole {
    private int contents;
    private boolean available = false;
    public synchronized int get() {
    while (available == false) {
    try {
    wait();
    } catch (InterruptedException e) { }
    available = false;
    notifyAll();
    return contents;
    public synchronized void put(int value) {
    while (available == true) {
    try {
    wait();
    } catch (InterruptedException e) { }
    contents = value;
    available = true;
    notifyAll();
    ***********ProducerConsumerTest.java***********
    public class ProducerConsumerTest {
    public static void main(String[] args) {
    CubbyHole c = new CubbyHole();
    Producer p1 = new Producer(c, 1);
    Consumer c1 = new Consumer(c, 1);
    p1.start();
    c1.start();

    instantiate another consumer.
    public class ProducerConsumerTest {
    public static void main(String[] args) {
    CubbyHole c = new CubbyHole();
    Producer p1 = new Producer(c, 1);
    Consumer c1 = new Consumer(c, 1);
    Consumer c2 = new Consumer(c, 2);
    p1.start();
    c1.start();
    c2.start();
    but then modify CubbyHole so that it checks that it has been consumed twice (as thats what you want, you said). Instead of using boolean available, use an integer flag that counts how many times its been consumed, and then reset the flag when it gets to 2. Something like that. Is this a college question? Do your homework. ha ha.

  • Business Package on Producer and Consumer in a FPN

    Hi Gurus,
       I need to know if we need to install the Same Business packages on both the producer and consumer or is it enough to install the Business Package only on the producer....
    Regards!

    Whats your scenario, typically one would go about installing business packages and other content on the producer or multiple producers and federate it with a consumer portal and provide access via the consumer.
    For example if you have a box which hosts ESS content, another box which hosts BI content and you have a global portal which is the box which all the end users will be accessing, then you simly have to install BP for ESS on the ESS box, create BI content on the BI box and display all this content via the consumer (global portal).
    Hope this helps.
    Good Luck!!
    GLM

  • Internal Error ORA-0600 when creating multiple consumer queue table

    Hi,
    I tried to create a multiple consumer queue table with the following statements:
    exec DBMS_AQADM.GRANT_TYPE_ACCESS ('system');
    create type Change_History_Trigger_Data as object(Col1 VARCHAR2(255), Col2 VARCHAR2(128), Col3 VARCHAR2(255), Col4 TIMESTAMP, Col5 VARCHAR2(64), Col6 VARCHAR2(64), Col7 NUMBER(8));
    Works fine till this stage. But the following statement produces an ORA-0600 internal error message.
    EXEC DBMS_AQADM.CREATE_QUEUE_TABLE ('change_history_queue_tbl','Change_History_Trigger_Data', 'tablespace my_tblspace','ENQ_TIME',TRUE,DBMS_AQADM.TRANSACTIONAL);
    ERROR at line 1:
    ORA-00600: internal error code, arguments: [kcbgtcr_4], [14392], [0], [1], [], [], [], []
    ORA-06512: at "SYS.DBMS_AQADM_SYS", line 2224
    ORA-06512: at "SYS.DBMS_AQADM", line 58
    ORA-06512: at line 1
    I tried creating the same queue table with Multiple consumer = FALSE, and it works fine. But not with multiple consumer = TRUE
    I'm running on Oracle9i Enterprise Edition Release 9.2.0.6.0
    Any possible solutions?

    Problem solved.
    The queue name was too long. Found a post with the same problem.
    Re: Create Queue Table ORA-00600 while dbms_aqadm.create_queue_table
    thanks anyway

  • Send data from producer to consumer

    Hi,
    I am trying on a sampe project with weblogic as both producer and consumer. I could send the data from consumer to producer to using Interceptors. Now, my requirement is to send data from producer back to consumer. I can do this using SimpleStateHolder, but I want a generic way like passing information in cookies/HTTP Request Headers from producer...etc and to retrieve them at consumer. This is because in my actual implementation the producer will be websphere.
    So, please can anyone tell me how to send data from producer to consumer ???
    Thanks,
    Anu

    Hello Anu,
    I believe WLP 10.2 requires some patches to get the consumer
    interceptor to properly access cookies coming from the producer, so
    that is probably why you aren't seeing the cookies. After reading your
    use-case, I don't think you will need to get these patches to get your
    use-case to work, but if you are still interested in the patches, I can
    find out the details for you.
    The reason the redirect code you posted isn't working is because the
    response has already been committed during the getMarkup operations and
    it is too late to redirect the page to a different URL, so the redirect
    is being ignored.
    The good news is that the functionality you want should all be fairly simple to implement.
    When the user opens the remote portlet, makes a selection and then
    submits it, the first thing that will happen is a WSRP
    BlockingInteraction call to the producer, to let the remote portlet
    know that a user has interacted with it. This happens before the
    GetMarkup operation, during a time when it is still legal to redirect
    to a different URL. In fact, the portlet on the producer is allowed to
    send a response indicating that the page should be redirected to a
    different URL.
    So in your remote portlet, you can have it look at the form values that
    were submitted during the BlockingInteraction call, and if the user
    selected the particular value that should be redirected to another
    portlet, the remote portlet can request a redirect. The only problem
    here is that your remote portlet doesn't know the URL to the portlet it
    wants to redirect to on the consumer side, but you can handle that in
    an interceptor on the consumer.
    So, rather than implement the IGerMarkupInterceptor, use the IBlockingInteractionInterceptor. For example:
    public sampleInterceptor implements IBlockingInteractionInterceptor
    // Other methods need to be implemented to do nothing...
    public Status.PostInvoke postInvoke(<code>IBlockingInteractionRequestContext requestContext,
    IBlockingInteractionResponseContext responseContext)</code>
    String redirectUrl = responseContext.getRedirectURL();
    if(redirectUrl != null)
    // The producer portlet wants to redirect- substitute the right consumer URL
    PageURL pageUrl =
    PageURL.createPageURL(requestContext.getHttpServletRequest(),
    requestContext.getHttpServletResponse),
    "voipTrunk_portal_page_11_page_12_page_13");
    responseContext.setRedirectURL(pageUrl.toString());
    This should be all that you need to do on the consumer side. It will
    automatically redirect for you to the URL you set in the interceptor,
    since the producer portlet requested a redirect.
    On the producer side, you will need to have the portlet send the
    redirect request during the BlockingInteraction operation. How you do
    this depends on what portlet type you are using and what producer you
    are using. For example, in WLP using a JSP portlet, you would need to
    use a backing file on the portlet, and have that class implement the
    JspBacking class:
    http://edocs.beasys.com/wlp/docs102/javadoc/com/bea/netuix/servlets/controls/content/backing/JspBacking.html
    Then, in the handlePostbackData method you would look for the special value and redirect if it exists, such as:
    public boolean handlePostbackData(HttpServletRequest request, HttpServletResponse response)
    String paramValue = request.getParameter("paramName");
    if((paramValue != null) && (paramValue.equals("specialValue"))
    // Need to send a redirect request
    PortletBackingContext pbc = PortletBackingContext.getPortletBackingContext(request);
    pbc.sendRedirect("http://anyUrlWillWork");
    return(true);
    return(false);
    Since the consumer interceptor is changing the redirect URL, any
    redirect URL the producer sends will work- it just needs to look like a
    valid, absolute URL to pass some simple checks on the producer.
    Backing files are documented here: http://e-docs.bea.com/wlp/docs102/portlets/building.html#wp1077130
    As I mentioned before, different portlet types and producers would do
    this differently. For example, I don't think WebSphere has backing
    files, and in JSR168 portlets a backing file is not needed- you would
    do the equivalent code in the JSR168 portlet's processAction() method
    (using javax.portlet.ActionResponse.sendRedirect(String URL) to send
    the redirect request). JSR168 portlets should work in both WLP and
    WebSphere, but I don't know the details of the portlet type you want to
    use on the WebSphere producer; if it isn't a JSR168 portlet, WebSphere
    must have some way equivalent to the backing file's handlePostbackData
    method to participate in a WSRP BlockingInteraction operation and
    request a redirect.
    No cookies or headers are required though, so I don't think you would
    need the patches to WLP 10.2 for the interceptor dealing with cookies.
    Hope this helps,
    Kevin

  • How to find out the JVM thread that is consuming high CPU

    I am using WL 10.3, JRockit JVM on Linux. I have taken thread dumps. How to find out the JVM thread that is consuming high CPU?
    I know how to map it Sun JVM on Solaris. I haven't done in on JRockit so far. Please advise.

    Check out some of Marcus Hirt's blog entries for details about how to use JRockit Mission Control. It's a very nice tool that should provide a lot of insight:
    http://blogs.oracle.com/hirt/

  • Produce multiple target nodes

    Hi Experts,
    In my SOAP to RFC scenario , the SOAP req contains one input value i.e. MAtnr . I have mapped this field with a field Mat_Number in RFC -Req . Its simply direct mapping . Its working for a single value perfectly .
    My requirement is If SOAP -Req contains many matnr values , Its not working . How can I build this MEss Mapping to produce multiple  Mat_Number field in RFC-Req.
    Presently It is MATNR----
    >MAT_NUMBER.
    Can you pls suggest how to build mapping to produce multiple MAT_NUMBER .
    Thanks.
    Drumi

    Mark,
    This is source and target structures.
    Source::
    MT                             1..1
       -Records                1..Unb
           -Matnr                 1..Unb
    Target::
    ZRFC                                 1..1
         -IMPORT                       1..1
                -Item                      0..Unb
                      - werks           0..1
    Here I have mapped matnr -
    > werks and Records -
    > item .
    Can you now explain If I want multiple werks values at target side .
    -Drumi

  • Multiple Consumer Object per Streaming Connection in AIR2.0

    HI,
    we require streaming server setup for our project.
    We are trying to minimize number of connections to the streaming server.
    My query is "If we have multiple Consumer object instance with same channel and destination, will all the Consumer instances share the same streaming connection or for every Consumer object instance a new Connection is created?"
    Thanks in advacne for your support.
    Regards,
    Shailendra

    Thanks doghouseJim, appreicate
    I tried to substitute onStatus function with your code (metadata) and as a result I don't have reported  error anymore.
    However, for strange reason, once the flash goes into a html document the video is not loaded...
    any idea?
    Cheers

  • Multiple Consumer object per Streaming Connection in AIR

    hi,
    We require streaming server setup for our project.
    We are trying to minimize the active connections to the server.
    My query is "If we are using multiple Consumer object instances with same channel and destination, will we have a single connection to the server shared by all Consumer instances or we'll be having different connection for each Consumer instance".
    Thanks in advance for your support
    Regards,
    Shailendra Sirohi

    Excellent answer.  It dovetails with the approach I've started to take here.  I'm using something called NetConnectionClient to catch server calls.  Does your NCMgr class extend NetConnection or EventDispatcher?
    Mine extends EventDispatcher and has a method like the following.  Just stuffs the message from the server into an object first before dispatching an event containing it:
            public function receiveChatMessage(msg:String):void
                var tempObj:Object = new Object();
                tempObj.msg = msg;
                dispatchEvent(new NetConnectionClientEvent("onReceiveChatMsg", tempObj));
    All cool there.  This works up to this point.
    I'm hazy after that though.  Who should listen for and handle the event?  I'd like my chat component to listen for and handle it directly, like in your scenario.  But my chat component is in a separate mxml file imported into the main app file.  I'm hazy on how to have it grab what it needs.
    I currently have the "application" listening for and handling the event.  The handler method just relays the call by calling a method on the chat component instance, like this:
    chat.receiveMessage(tempObj); //tempObj contains the message
    I think that's too many relays of the same call, from the NetConnectionClient class, to the main application file, down to the custom chat component.  I'd like to cut out a leg of that trip.
    Should I have the chat component instance itself be listening, like this?
                chat.addEventListener("onReceiveChatMessage", chat.receiveChatMsg);
    Is that a proper relay of the dispatched event to the target component.  The syntax doesn't seem proper to me.  I feel like something's wrong with the design of the last leg of the relay here.

  • Producer and Consumer Issue

    Hi,
    Do we need to consume all the portles of the producer from portal admin console?
    or is there a way to use the .Portal file directly as all the portlets of the producer are consumed already?
    Edited by: user8894463 on Dec 15, 2009 2:34 PM

    Hi
    1. In 10.x (not sure about 9.x), from Workshop IDE, we can create like Standalone Books and Pages that can be Consumed as Whole on the Consumer side. From IDE, right click project and select New -> Other -> Expand Weblogic Portal and you should see "Book", "Page". Once this is done, you can add all your portlets on these stuff. Now on Consumer Side, when you register the Producer, you do See these Books and Pages. So if you consume full Book or Page, you will get all the Portlets also. This is very handy instead of creating and consuming "n" number of portlets on consumer manually. Also if your consumer portal is created from Workshop IDE, you can choose above menu option and select "Remote Book" or "Remote Page" and this asks for Remote Producer URL and consume that entire book or page. All that matters is on Producer side, you will not create Books and Pages in .portal file. Instead use the first above option like Create New Other -> Book or Page.
    2. By default, when you register Producer, it just shows list of all Portlets from Producer. It is upto you on Consumer side, what portlets to consumer or not and create corresponding proxy portlets. By default, all portlets created from WLP are Remotely consumable.
    The concept of creating standalone Books and Pages and consuming them as a whole on Consumer side is really cool.
    HTH
    Ravi Jegga
    Edited by: Ravi Jegga on Dec 15, 2009 6:25 PM

  • Multiple group example is not working

    i run the multiple groups example in cocomo
    I subjected to one problem
    me as owner, my friend as guest entered into room
    i created one group group1. myself added into that group.
    my friend was in default.
    if i am trying to send mess. no connection . That was good
    After that i added my friend into group1.
    now there is connection between us. message was sent.
    now i remove my friend from my group1.
    if i am trying to send the message to my friend, still the message was sent to my friend.
    friends i am trying lot to make the disconnection after removing my friend from group1.
    i am not able to do.
    just exactly i run multiple groups without any change.

    Hi,
    But inv_no is diferent for each row, isn't? So, what value do you want to show?
    Example:
    Connected to Oracle Database 10g Express Edition Release 10.2.0.1.0
    Connected as hr
    SQL>
    SQL> with pradeep as(
      2  select 1 as re, 2 as zo, 1 as call_no, 1 as inv_no from dual union all
      3  select 1 as re, 2 as zo, 1 as call_no, 2 as inv_no from dual union all
      4  select 1 as re, 2 as zo, 1 as call_no, 3 as inv_no from dual union all
      5  select 1 as re, 2 as zo, 1 as call_no, 4 as inv_no from dual union all
      6  select 1 as re, 3 as zo, 1 as call_no, 5 as inv_no from dual union all
      7  select 1 as re, 3 as zo, 1 as call_no, 6 as inv_no from dual
      8  )
      9  SELECT re,
    10         zo,
    11         call_no,
    12         COUNT(*) AS cnt
    13    FROM pradeep
    14   GROUP BY re,
    15            zo,
    16            call_no
    17  HAVING COUNT(*) > 1;
            RE         ZO    CALL_NO        CNT
             1          2          1          4
             1          3          1          2
    SQL> Regards,

  • Contacts producing multiple entries as does calendar . How to stop and fix please.

    Contacts producing multiple entries as does Calender. How to stop and fix pls?

    ok easiest way it to restore to factory setting and start from there. When you go to do your first sync you don’t “sync contacts or calendar”. When you add mobile me onto your Ipad select all the services that you want to enable and then mobile me will keep everything in sync.
    If you need futher steps let me know

  • Diff between Multiple Threading and Multiple instance.

    Hi ,
    what is the main diff between Multiple Threading and Multiple instance?
    Please give me the answer

    Satti4Java wrote:
    Hi ,
    what is the main diff between Multiple Threading and Multiple instance?The main difference (not "diff") is that the first one ends with the word "Threading" and the second one ends with the word "instance".
    Really. Seriously. Now if you had some industry standard phrases you were comparing, there might be a useful discussion. But those are just words strung together. If that's a homework question, I recommend you find a different teacher.

  • Allowing first multiple consumer to dequeue; deny others

    Hi.
    We have defined a multiple consumer queue, and in it, we would like to be able to post a message to one or more consumers, but have the message fully consumed by the first consumer that dequeues it.
    For instance, suppose a message is enqueued for 'Blue' and 'Red.' The way I understand AQ, both Blue and Red will have to dequeue the record before it is removed. What if, instead, I would like the record to be dequeued by only one of the consumers. So that if Blue dq's it, Red will never see it; and if Red dq's it, Blue will never see it.
    Is there a way to do this?
    Thanks.

    It sounds like all you need to do is to set multiple listeners to false. Multiple listeners implies that the message will be delivered to all listeners. You can set multiple listeners to false but have more than one application pulling (or being event driven) from the queue. In that case only one connection will get the message.
    thanks, don.

Maybe you are looking for

  • Elements 10 not working and uninstall not working either help please?

    Elements 10 does not work and I have tried to uninstall it with the intention of re-installing.   When I press un-install it tells me it is still uninstalling or changing the program but this has been happening for three hours?  Windows installer is

  • Two annoying bugs when exiting guided acces via Touch ID

    When exiting guided access on my iPad Air 2 (iOS 8.1.3) via Touch ID, I encounter the following strange behavior: 1. the disabled areas I defined in the guided access mode (the "greyed-out" areas where touch input is not accepted) remain as grey area

  • Message no :amoc001 the system couldnt automatically create a transfer docu

    hi, message no :amoc001 the system couldnt automatically create a transfer document hi all when i follow the steps in this link Message no. AMOC005 i just end up with the problem above when i tried to change the business area normally the system auto

  • Scheduled GridControl jobs get not executed

    Hello, I have a really strange behaviour lately with the GridControl jobs: We have several GridControl jobs which are scheduled (e.g. from monday til friday at 05:00 am). In usual, they get executed at the scheduled time. But some of them don't get e

  • Location registration with runtime..

    HI All, How can we register LOCATION with runtime.. I face this error. When I deploy mapping it will give error location not register with runtime?? HOw to solve this problem?? DJ