Reputation: 906
I have this very basic script which performs a Redis server request but I do not understand multithreading enough as to successfully make it run in parallel. This is what I have in my main()
method
Jedis jedis1 = new Jedis("10.10.25.54", 6381);
Jedis jedis2 = new Jedis("10.10.25.54", 6382);
Jedis jedis3 = new Jedis("10.10.25.54", 6383);
Jedis jedis4 = new Jedis("10.10.25.54", 6384);
Jedis jedis5 = new Jedis("10.10.25.54", 6385);
Jedis jedis6 = new Jedis("10.10.25.54", 6386);
Jedis jedis7 = new Jedis("10.10.25.54", 6387);
Jedis jedis8 = new Jedis("10.10.25.54", 6388);
// The bit i would like to learn how run in parallel
//
System.out.println(jedis1.eval(SCRIPT, 0).toString());
System.out.println(jedis2.eval(SCRIPT, 0).toString());
System.out.println(jedis3.eval(SCRIPT, 0).toString());
System.out.println(jedis4.eval(SCRIPT, 0).toString());
System.out.println(jedis5.eval(SCRIPT, 0).toString());
System.out.println(jedis6.eval(SCRIPT, 0).toString());
System.out.println(jedis7.eval(SCRIPT, 0).toString());
System.out.println(jedis8.eval(SCRIPT, 0).toString());
Upvotes: 0
Views: 180
Reputation: 654
Multithreadding and concurrency is a fairly large topic in Java, too big to answer in a single question, and there any many possible solutions. However I recommend reading the Orical Concurrency tutorials.
My approach would be:
ExecutorService es = Executors.newCachedThreadPool();
es.submit(new RunJedis(jedis1));
es.submit(new RunJedis(jedis2));
es.submit(new RunJedis(jedis3));
es.submit(new RunJedis(jedis4));
es.submit(new RunJedis(jedis5));
es.submit(new RunJedis(jedis6));
es.submit(new RunJedis(jedis7));
es.submit(new RunJedis(jedis8));
class RunJedis{
Jedis jedis;
RunJedis(Jedis jedis1){
this.jedis=jedis1;
}
void run(){
System.out.println(jedis.eval(SCRIPT, 0).toString());
}
}
However, this wouldn't be guaranteed to use multiple threads. You are leaving it up to the executor service to decide how is best.
Upvotes: 2