Home  >  Java 7

ThreadLocalRandom Java Example

By Arvind Rai, January 03, 2014
java.util.concurrent.ThreadLocalRandom has been introduced in jdk 7. Like java.util.Random, ThreadLocalRandom is also a random number generator. But ThreadLocalRandom is used in concurrent environment and isolated to current thread. In multithread environment, each thread can get a random number parallel to other thread with the help of ThreadLocalRandom. The random number obtained by one thread has not been affected by the thread. Whereas java.util.Random provides random number globally. So ThreadLocalRandom is a good feature in multithreaded environment. ThreadLocalRandom is used within ForkJoinTask. Find the some methods of ThreadLocalRandom.

current() in ThreadLocalRandom

This method returns ThreadLocalRandom instance for the current thread. ThreadLocalRandom can be initialized as below.
ThreadLocalRandom  random = ThreadLocalRandom.current(); 

nextInt in ThreadLocalRandom

nextInt(int least,int bound) returns the next pseudo number . We can pass the least limit and max limit. There are more method like nextDouble, nextLong. So finally we can get random number as below
int i = ThreadLocalRandom.current().nextInt(1, 10);	
ThreadLocalRandom is normally used with ForkJoinTask. Find the example below.
ThreadLocalRandomDemo.java
package com.concretepage.util.concurrent;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.ThreadLocalRandom;
public class ThreadLocalRandomDemo {
	public static void main(String[] args) {
		ForkJoinPool pool = new ForkJoinPool();
		TestTask task1 = new TestTask("Task one");
		TestTask task2 = new TestTask("Task two");
		pool.invoke(task1);
		pool.invoke(task2);
    }
}	
class TestTask extends ForkJoinTask<String> {
	private String msg = null;
	public TestTask(String msg){
		this.msg = msg;
	}
	private static final long serialVersionUID = 1L;
	@Override
	protected boolean exec() {
	   int i = ThreadLocalRandom.current().nextInt(1, 10);		
	   System.out.println("ThreadLocalRandom for "+msg+":"+i);
	   return true;
	}
	@Override
	public String getRawResult() {
		return null;
	}
	@Override
	protected void setRawResult(String value) {
	}
}
In the example there is a ForkJoinTask implementation and inside exec() method of ForkJoinTask, we obtained the random number by ThreadLocalRandom. We have run two ForkJoinTask to test the random number generation. Run the example many time and every time you will get random numbers. Sample output is as below.
ThreadLocalRandom for Task one:5
ThreadLocalRandom for Task two:2
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us