Zookeeper to achieve merchandise seconds kill snapping

Source: Internet
Author: User

 Packagecom.test;Importjava.io.IOException;Importjava.util.List;ImportJava.util.concurrent.CyclicBarrier;ImportOrg.apache.zookeeper.CreateMode;Importorg.apache.zookeeper.KeeperException;Importorg.apache.zookeeper.WatchedEvent;ImportOrg.apache.zookeeper.Watcher;ImportOrg.apache.zookeeper.Watcher.Event.EventType;ImportOrg.apache.zookeeper.ZooDefs.Ids;ImportOrg.apache.zookeeper.ZooKeeper;ImportOrg.apache.zookeeper.data.Stat; Public classMain { Public Static voidMain (string[] args)throwsIOException, Keeperexception, interruptedexception {ZooKeeper ZK=NewZooKeeper ("127.0.0.1", 2000,NULL); Stat St= Zk.exists ("/goods",false); if(St = =NULL) {zk.create ("/goods",New byte[0], Ids.open_acl_unsafe, createmode.persistent); } string[] Goods= {"Iphone6s", "Xiaomi Mobile Power" };  for(String g:goods) {zk.create ("/goods/" + G,New byte[0], Ids.open_acl_unsafe, createmode.ephemeral); }        intThreadCount = 5; Cyclicbarrier CB=NewCyclicbarrier (ThreadCount);//to better represent concurrency, the Cyclicbarrier class is used here         for(inti = 0; i < ThreadCount; i++) {            //use multithreading to touch your multi-user            NewThread (NewThread1 (CB)). Start ();    } System.in.read (); }    Static classThread1ImplementsRunnable {ZooKeeper ZK=NULL;        Cyclicbarrier CB; //have you ever robbed a product ?        BooleanIsnotget =true;  PublicThread1 (Cyclicbarrier cb) { This. cb =CB; }        Private voidSnatchgoods ()throwsException {//Get Product Inventorylist<string> goodslist = Zk.getchildren ("/goods",true);//get a list of items and monitor changes if you can monitor other items again if you don't grab the same item with other users            if(Goodslist.isempty ()) {//Commodity inventory is empty, indicating that the goods robbedSystem.out.println (Thread.CurrentThread (). GetName () + "No merchandise"); } Else {                //get the first itemString goods = goodslist.get (0); Try {                    //Remove the product node from memory, indicating snapping, if the deletion fails, it means that the product has not been robbed and entered into the following catch blockZk.delete ("/goods/" + goods, 1); //restrict each user to snapping up only one item, set false to indicate that it has been snappedIsnotget =false; System.out.println (Thread.CurrentThread (). GetName ()+ "grabbed" +goods); } Catch(Exception e) {}}} @Override Public voidrun () {Try{ZK=NewZooKeeper ("127.0.0.1:2181", 2000,NewWatcher () {@Override Public voidprocess (Watchedevent event) {Try{EventType type=Event.gettype (); if(isnotget) {if(Type = =eventtype.none) {//The first time the user accesses, then immediately executes the product snapping upSnatchgoods (); } Else if(Type = =eventtype.nodechildrenchanged) {//Snapping up one item and then snapping up anotherSnatchgoods (); }                            }                        } Catch(Exception e) {System.out.println (E.getmessage ());            }                    }                }); } Catch(Exception e) {e.printstacktrace (); }        }    }}
    1. Simulate multi-user snapping with multithreading
    2. The first time the user accesses, then immediately executes the product snapping up
    3. Snapping up one item and then snapping up another
    4. Commodity inventory is empty, indicating that the goods robbed

Zookeeper to achieve merchandise seconds kill snapping:

Second-kill activities are some of the shopping platform launched the focus of popular activities, the general number of small goods, the price is very cheap, limited to start the purchase time, will be in seconds in the time of the purchase of a blank. such as the original price thousand yuan even million of goods sold at a dollar price, but only one, in a certain time of the day to start selling, which caused a lot of people to rob this commodity.

Get a list of items and monitor changes if you can monitor other items again if you don't grab the same item with other users

Snapping up one item and then snapping up another

Run multiple times to print out the following results:

thread-4-Eventthread grabbed the iphone6sthreadEventthread grabbed the millet mobile power thread  Eventthread didn'tgrab the product thread-Eventthread didn't grab the product thread-0-eventthread didn't grab the merchandise


Thread-3-eventthread grabbed iphone6s.
Thread-2-eventthread grabbed the millet. Mobile Power
Thread-4-eventthread didn't grab the merchandise.
Thread-1-eventthread didn't grab the merchandise.
Thread-0-eventthread didn't grab the merchandise.


Thread-0-eventthread grabbed iphone6s.
Thread-3-eventthread grabbed the millet. Mobile Power
Thread-4-eventthread didn't grab the merchandise.
Thread-2-eventthread didn't grab the merchandise.
Thread-1-eventthread didn't grab the merchandise.


Thread-2-eventthread grabbed iphone6s.
Thread-4-eventthread grabbed the millet. Mobile Power
Thread-0-eventthread didn't grab the merchandise.
Thread-3-eventthread didn't grab the merchandise.
Thread-1-eventthread didn't grab the merchandise.

As you can see, two pieces of merchandise, multiple threads are snapped up, and there are always only two threads that rob different items.

Zookeeper to achieve merchandise seconds kill snapping

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.