實戰Memcached緩衝系統(6)Memcached CAS的多線程程式執行個體

來源:互聯網
上載者:User

1. 來源程式

package com.sinosuperman.memcached;import java.io.IOException;import java.net.InetSocketAddress;import net.spy.memcached.CASResponse;import net.spy.memcached.CASValue;import net.spy.memcached.MemcachedClient;public class Test {private static MemcachedClient client = null;static {try {client = new MemcachedClient(new InetSocketAddress("localhost", 11211));} catch (IOException o) {}}public static void main(String[] args) throws Exception {client.set("numberss", 1800, 1);Test testObj = new Test();for (int i = 0; i < 10; i++) {testObj.new ThreadTest("Thread-" + (i + 1)).start();}}private class ThreadTest extends Thread {private  MemcachedClient client = null;ThreadTest(String name) throws IOException {super(name);client = new MemcachedClient(new InetSocketAddress("localhost", 11211));}public void run() {int i = 0;int success = 0;while (i < 10) {i++;CASValue<Object> uniqueValue =client.gets("numberss");CASResponse response = client.cas("numberss",                    uniqueValue.getCas(), (Integer)uniqueValue.getValue() + 1);if (response.toString().equals("OK")) {success++;}if (i == 10)System.out.println(Thread.currentThread().getName() + " " +  i                   + " time " + " update oldValue : " + uniqueValue.getValue()                   +  " , result : " + response);}if (success < 10) {Count.incr(10 - success);System.out.println("Test counter: " + Count.get());}}}public static class Count {private static int counter = 0;public static void incr(int x) {counter += x;}public static int get() {return counter;}}}

2. 輸出結果:

Thread-1 10 time  update oldValue : 14 , result : EXISTSTest counter: 6Thread-2 10 time  update oldValue : 14 , result : EXISTSTest counter: 15Thread-3 10 time  update oldValue : 17 , result : EXISTSTest counter: 22Thread-5 10 time  update oldValue : 17 , result : EXISTSTest counter: 27Thread-4 10 time  update oldValue : 20 , result : OKTest counter: 33Thread-8 10 time  update oldValue : 27 , result : OKTest counter: 36Thread-6 10 time  update oldValue : 28 , result : EXISTSTest counter: 43Thread-10 10 time  update oldValue : 31 , result : EXISTSTest counter: 52Thread-9 10 time  update oldValue : 31 , result : OKTest counter: 60Thread-7 10 time  update oldValue : 35 , result : OKTest counter: 65

3. 分析

我們可以看到,未成功的次數最終為65,資料值最終為35,兩者的和剛好是100,正好符合我們的實驗結果預期。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.