Producer consumer model of Java concurrency

Source: Internet
Author: User
Tags int size

Producer and consumer models are classic synchronization issues in the operating system. The problem was first proposed by Dijkstra to demonstrate the semaphore mechanism it proposed.

The description of the classic producer and consumer model is: There is a group of producers in the process of producing products. And make these products available to consumer processes to consume. In order for the producer and consumer processes to execute concurrently, a buffer pool with n buffers is set between them, and the producer process puts the products it produces into a buffer. The consumer process can take the product away from a buffer to consume. Although all producer processes and consumer processes are executed asynchronously. However, they must be kept in sync, that is, they do not agree with the consumer process to an empty buffer to fetch the product, nor do they agree with the producer process to deliver the product to a buffer that is already full and has not been taken away.

First, let's review the guidelines that should be followed in the synchronization mechanism in the operating system:

    1. Spare : When there is no process in the critical section, it should be agreed that a request to enter the critical section of the process into the critical area;
    2. busy waiting : When an existing process enters the critical section, other processes attempting to enter the critical section must wait.
    3. Limited Wait : The process of requesting access to critical resources should be guaranteed to enter its critical area within a limited time. Avoid falling into the "death" state.
    4. The right to wait : When the process cannot enter its own critical section, the processor should be released immediately. Lest the process be caught in a "busy wait";

      There are a few things to be sure about in the producer and consumer models:
      1. When a producer places a product in the cache queue, the consumer cannot take the product.
      2. When the consumer takes the product from the cache queue. Producers cannot put products.
      3. At the same time only one producer was able to place products in the cache queue.
      4. At the same time, only one consumer is able to fetch products from the cache queue.
      5. The producer cannot place the product in the cache queue when the cache queue is full.
      6. When the cache queue is empty, consumers cannot fetch products from the cache queue.

The cache queue in this sample mimics the Arrayblockingqueue in the Java JDK, which is a blocking queue that automatically suspends the producer thread itself when the cache pool is full, and automatically suspends the consumer thread when the cache pool is empty.

Cache Pool

Public class Pool<E> {    /** Queue Maximum length * /    Privateint MaxSize = +;/** Queue Default length * /    PrivateStaticFinalint defaultsize = -;/** Resource pool * /    PrivateObject[] OBJS;/** Team head * /    Privateint front;/** (end of Team) *    Privateint rear;number of/** elements * /    Privateint nitems;/** Main Lock guarding All Access * /    FinalReentrantlock lock;/** Condition for waiting takes * /    Private FinalCondition Notempty;/** Condition for waiting puts * /    Private FinalCondition Notfull;Privateint usesize =0; Public Pool () { This(defaultsize);    Usesize = defaultsize; } public Pool (int size) {if(Size <0)Throw NewIndexoutofboundsexception (); size = size > MaxSize?        Maxsize:size;        usesize = size; OBJS =NewObject[size]; Front =0; Rear =-1; Nitems =0; Lock =NewReentrantlock (true);        Notempty = Lock.newcondition ();    Notfull = Lock.newcondition (); }/** into the team * *    Privatevoid Queue (E e) {if(Rear = = usesize-1) Rear =-1;        Objs[++rear] = e;        nitems++;    Notempty.signal (); }/** out of the team * *    Privatee dequeue () {e E = (e) objs[front++];if(front = = usesize) Front =0;        nitems--; Notfull.signal ();returnE }/** Incoming team resource pool full will hang the queued thread * /public void Offer (E e)throwsinterruptedexception {FinalReentrantlock lock = This. Lock; Lock.lock ();Try{ while(Nitems = = objs.length) notfull.await ();            Queue (e); System.out.println (the students entered the team. The current pool has "+ Nitems +"Famous students"); }finally{Lock.unlock (); }    }/** out of team resource pool empty will hang the outbound thread * /Public E Poll ()throwsinterruptedexception {FinalReentrantlock lock = This. Lock; Lock.lock ();Try{ while(Nitems = =0) notempty.await ();            E e = dequeue (); System.out.println ("The students are out of the team, the current pool has"+ Nitems +"Famous students");returnE }finally{Lock.unlock (); }    }/** is full * *public Boolean isfull () {FinalReentrantlock lock = This. Lock; Lock.lock ();Try{returnNitems = = MaxSize?true:false; }finally{Lock.unlock (); }    }/** Whether the inference is empty * /public Boolean isEmpty () {FinalReentrantlock lock = This. Lock; Lock.lock ();Try{returnNitems = =0?true:false; }finally{Lock.unlock (); }    }/** Returns the number of elements in the queue * /public int size () {FinalReentrantlock lock = This. Lock; Lock.lock ();Try{return  This. Nitems; }finally{Lock.unlock (); }    }   }

Test model

 Public classStudent {PrivateString name;Private intAge PublicStringGetName() {returnName } Public void SetName(String name) { This. name = name; } Public int Getage() {returnAge } Public void Setage(intAge) { This. Age = Age; }}

Main class

 Public  class PM {    Privatepool<student> pools =NewPool<student> ( +); Public Static voidMain (string[] args) {pm PM =NewPM (); Executorservice executor = Executors.newfixedthreadpool (6); Executor.execute (PM.NewConsume ()); Executor.execute (PM.NewConsume ()); Executor.execute (PM.NewConsume ()); Executor.execute (PM.NewProduce ()); Executor.execute (PM.NewProduce ()); Executor.execute (PM.NewProduce ()); } class produce implements Runnable {@Override Public voidRun () { while(true) {Try{Pools.offer (NewStudent ()); }Catch(Interruptedexception e)                {E.printstacktrace (); }            }        }    } class consume implements Runnable {@Override Public voidRun () { while(true) {Try{Pools.poll (); }Catch(Interruptedexception e)                {E.printstacktrace (); }            }        }    }}

Execution Result:

Producer consumer model of Java concurrency

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.