Skip to content

Instantly share code, notes, and snippets.

@coopernurse
Last active September 11, 2017 20:51
Show Gist options
  • Save coopernurse/b2b60de5e1007483a1c56e426300c459 to your computer and use it in GitHub Desktop.
Save coopernurse/b2b60de5e1007483a1c56e426300c459 to your computer and use it in GitHub Desktop.
RedisThreadingTest
package com.imprev.util;
import com.imprev.soa.redis.JedisRetry;
import com.imprev.soa.util.Log4JInit;
import com.imprev.soa.util.RandomString;
import com.imprev.soa.util.RedisTTLCache;
import org.junit.Test;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import static org.junit.Assert.fail;
/**
* Author: James Cooper - james@bitmechanic.com
* Date: 9/11/17
*/
public class RedisThreadingTest {
static {
Log4JInit.init();
}
@Test
public void multithreadedTest() throws Exception {
JedisRetry jedisRetry = new JedisRetry();
jedisRetry.setPool(new JedisPool("127.0.0.1", 6379));
RedisTTLCache ttlCache = new RedisTTLCache(jedisRetry);
int threadCount = 20;
int iterationsPerThread = 100000;
int uniqueKeys = 100;
int ttlSeconds = 3600;
final Random rand = new Random();
final Map<String,String> map = Collections.synchronizedMap(new HashMap<>());
final List<String> errors = Collections.synchronizedList(new ArrayList<>());
final List<Thread> threads = new ArrayList<>();
for (int i = 0; i < uniqueKeys; i++) {
String key = String.valueOf(i);
String val = RandomString.getAlphaNumeric(20);
map.put(key, val);
ttlCache.put(key, val, ttlSeconds);
}
for (int i = 0; i < threadCount; i++) {
threads.add(new Thread(() -> {
for (int z = 0; z < iterationsPerThread; z++) {
String key = String.valueOf(rand.nextInt(uniqueKeys));
String newVal = RandomString.getAlphaNumeric(20);
synchronized (key.intern()) {
String oldVal = map.get(key);
String oldValRedis = ttlCache.get(key);
if (rand.nextBoolean()) {
map.put(key, newVal);
ttlCache.put(key, newVal, ttlSeconds);
}
if (!oldVal.equals(oldValRedis)) {
errors.add("key: " + key + " oldVal: " + oldVal + " != " + oldValRedis);
}
}
}
}));
}
for (Thread t : threads) {
t.start();
}
for (Thread t : threads) {
t.join();
}
if (errors.size() > 0) {
fail("Errors: " + errors.size());
for (String err : errors) {
System.out.println(err);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment