JAVA Concurrent Programming-Application

Source: Internet
Author: User

Mention Java multithreading inevitably some people will head big, many concepts are very understanding but really to the actual combat time is not know how to operate, the following on the actual project to say multithreaded application.


Business requirements:

Example: Bulk INSERT 100,000 user's related event coupons

How to do it: use a fixed 10-size thread pool to do it, and process 1000 data inserts at a time


Thread class: Note Implementing the Callable<integer> interface is the thread class that can get the return value

public class Insertbatchthread implements callable<integer> {    private int vdate;    Private I NT uid;    private int count;    Private fundsinfomapper fundsinfomapper;    private Wmpsday Intermapper wmpsdayintermapper;    Private DataSource datasource;    public Wmpsdayintermapper Getwmpsdayintermapper () {        if (null = = Wmpsdayintermapper) {          & nbsp Synchronized (this) {                if (null = = Wmpsdayintermapper) {  &nbsp ;                 Wmpsdayintermapper = Springcontextutils.getbean (" Wmpsdayintermapper ");               }           }& nbsp      }        return wmpsdayintermapper;   }    public fundsinfom Apper Getprocommfundsinfomapper (){        if (null = = Fundsinfomapper) {            synchronized (this) {                 if (null = = Fundsinfomapper) {          & nbsp         Fundsinfomapper = Springcontextutils.getbean ("Fundsinfomapper");               }           }       }        return fundsinfomapper;   }       /**     * parameterless constructor   &NBSP ;  */    Public Insertbatchthread () {   }   /**     * parameterless constructor   &NBSP ;  */    public insertbatchthread (int vdate,int uid,int count) {        This.vdate=vdate ;        this.uid=uid;        this.count=count;        THIS.FU Ndsinfomapper=getfunDsinfomapper ();        This.wmpsdayintermapper=getwmpsdayintermapper ();           }   /**     * Multithreading prescribes a good method, if inheriting the thread class you must implement this method      */     Public Integer call () {        int result = -1;        Try {  & nbsp        //operation             list<integer> listUsers = Fundsinfomapper. Selectuserforinsertbatch (Count *, +);                    &N Bsp  //BULK Insert User Activity coupon record table             list<wmpsdayinter> Listonepagedayinner = Wmpsdayintermapper.selectbyinsertbatch (vdate,listusers.get (0), Listusers.get (Listusers.size ()-1));            Wmpsdayinterinsertbatch (Listonepagedayinner);       }catch (Exception E ) {            ResUlt=count;       }        return  result;   }   //BULK INSERT User Activity coupon Record form--jdbc    public int[] Wmpsdayinterinsertbatch (list<wmpsdayinter> listonepage) throws exception{        datasource=  springcontextutils.getbean ("DataSource");        PreparedStatement PS = datasource.getconnection (). Preparestatement ("INSERT Ignore into t_a (UID, Inter, CDate) Val UEs (?,?,?) ");         for (Wmpsdayinter oneobj:listonepage) {            Ps.setint (1,o Neobj.getuid ());            Ps.setbigdecimal (2, Oneobj.getinter ());      & nbsp     Ps.setbigdecimal (3,oneobj.getcdate ());            Ps.addbatch ();       }        return Ps.executebatch ();   }    }

the corresponding business implementation class:

/** * Event Coupon */@Service ("Fundsinfoservice") public class Fundsinfoserviceimpl extends Baseservice<procommfundsinfo, Fundsinfoexample> implements Ifundsinfoservice {private final static Logger Logger = Loggerfactory.getlogger (fundsi    Nfoserviceimpl.class);    @Autowired private Fundsinfomapper Fundsinfomapper;        Public Fundsinfoserviceimpl () {} @Override public void Insertdayinter (integer vdate, integer uid) {//Activity coupon condition judgment if (vdate = = NULL | | vdate.intvalue () <= 0 | | uid = = NULL | | uid.intvalue () < 0) {Logger.error ("=i        Nsertdayinter=>error,vdate= "+ Vdate +", uid= "+ uid);            } else {//statistics eligible user int totalnum = Fundsinfomapper.countforinsertbatchbyuser ();            list<integer> listexception = new arraylist<integer> ();            Initialize first batch start value int startrow = 0;                               try {//fixed size thread pool Executorservice fixedthreadpool = Executors.newfixedthreadpool (10); for (int i = 0; i<= Math.floor (totalnum/1000);                    i++) {future<integer> future = Fixedthreadpool.submit (new Insertbatchthread (vdate, UID, i));                    if (Future.get () >=0) {Listexception.add (Future.get ());                                   }//Event Coupon is sent out, verify if there is an omission, if any, fix if (listexception.size () >0) { for (int i = 0; I <= listexception.size (), i++) {future<integer> future = Fixedthreadpoo                        L.submit (New Insertbatchthread (Vdate, uid, listexception.get (i)));                        if (Future.get () >=0) {Listexception.add (Future.get ()); }}}}catch (Exception e) {logger.error ("<=            Insertdayinter=>error ", e);    }} logger.info ("<=insertDayInter=>"); }  }



The problem is that when we need to use multi-threaded operations, it is common to query, then insert, but at this point, if we do not have a reasonable dimension to split the data, it is easy to create a deadlock. For example, if we do not allocate the dimension reasonably, it is possible for batch to process the same data at the same time as batch two, both the query and the update, each other needs the other party's lock release to continue execution, resulting in deadlock.




JAVA Concurrent Programming-Application

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.