# Collection of code snippets by Arne Vajhøj 
# (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
import hazelcast
import multiprocessing
import time

NTHREADS = 100
NOPS = 10000

def test1():
    cfg = hazelcast.ClientConfig()
    cli = hazelcast.HazelcastClient(cfg)
    cache = cli.get_map("performance_cache")
    for i in range(NOPS//NTHREADS):
        hot = cache.get("hot").result()
        hot = hot + 1
        cache.put("hot", hot)
    cli.shutdown()

def test2():
    cfg = hazelcast.ClientConfig()
    cli = hazelcast.HazelcastClient(cfg)
    cache = cli.get_map("performance_cache")
    lck = cli.get_lock("hot").blocking()
    for i in range(NOPS//NTHREADS):
        lck.lock()
        hot = cache.get("hot").result()
        hot = hot + 1
        cache.put("hot", hot)
        lck.unlock()
    cli.shutdown()

def test3():
    cfg = hazelcast.ClientConfig()
    cli = hazelcast.HazelcastClient(cfg)
    cache = cli.get_map("performance_cache")
    for i in range(NOPS//NTHREADS):
        done = False
        while not done:
            hot1 = cache.get("hot").result()
            hot2 = hot1 + 1
            done = cache.replace_if_same("hot", hot1, hot2).result()
    cli.shutdown()

def test4():
    cfg = hazelcast.ClientConfig()
    cli = hazelcast.HazelcastClient(cfg)
    cache = cli.get_map("performance_cache")
    counter = cli.get_atomic_long("superhot").blocking()
    for i in range(NOPS//NTHREADS):
        counter.add_and_get(1)
    cli.shutdown()

def test(lbl, f, usecounter):
    cfg = hazelcast.ClientConfig()
    cli = hazelcast.HazelcastClient(cfg)
    cache = cli.get_map("performance_cache")
    t1 = time.time()
    cache.put("hot", 0)
    if usecounter:
        counter = cli.get_atomic_long("superhot").blocking()
        counter.set(0)
    t = []
    for i in range(NTHREADS):
        t.append(multiprocessing.Process(target=f, args=()))
    for i in range(NTHREADS):
        t[i].start()
    for i in range(NTHREADS):
        t[i].join()
    if usecounter:
        cache.put("hot", counter.get())
    hot = cache.get("hot").result()
    t2 = time.time()
    print("%s : %d = %d (%d ms)" % (lbl, hot, NOPS, (t2 - t1) * 1000))
    cli.shutdown()

if __name__ == '__main__':
    test("No handling", test1, False);
    test("Locking", test2, False);
    test("Replace with check", test3, False);
    test("Atomic increment", test4, True);
