21 Ekim 2016 Cuma

ThreadLocalRandom Sınıfı

Giriş
Şu satırı dahil ederiz.
import java.util.concurrent.ThreadLocalRandom;
Bu sınıf multi-thread programlarda daha iyi performans almak için kullanılıyor. Kodu şöyle
public class ThreadLocalRandom extends Random {
 ...
}
Random sınıfından kalıtıyor. Açıklaması şöyle. Yani Random sınıfı synchronized olduğu için multi-threaded kullanımda performansı iyi değil. Bu yüzden synchronized olmayan ThreadLocalRandom sınıfı geliştirilmiş.
The key problem is a lot of the code is legacy and can't (easily) be changed - Random was designed to be "thread-safe" by synchronizing all its methods. This works, in that instances of Random can be used across multiple threads, but it's a severe bottleneck as no two threads can simultaneously retrieve random data. A simple solution would be to construct a ThreadLocal<Random> object thereby avoiding the lock contention, however this still isn't ideal. There's still some overhead to synchronized methods even when uncontested, and constructing n Random instances is wasteful when they're all essentially doing the same job.

So at a high-level ThreadLocalRandom exists as a performance optimization,
Sonar
Sonar ThreadLocalRandom sınıfının kullanılmasına itiraz ediyor. SecureRandom kullanılmasını öneriyor. Açıklaması şöyle
Instances of ThreadLocalRandom are not cryptographically secure. Consider instead using SecureRandom in security-sensitive applications.
Ben Collections.shuffle() metodunu kullandım

current metodu
Şöyle yaparız.
ThreadLocalRandom random =ThreadLocalRandom.current();
longs metodu
Şöyle yaparız. Belirten sayı kadar eleman içeren bir LongStream döndürür.
ThreadLocalRandom.current().longs(10_000_000);
nextInt metodu
Örnek
Şöyle yaparız.
// nextInt is normally exclusive of the top value,
// so add 1 to make it inclusive
random.nextInt (min, max + 1);
Örnek
Listeden rastgele bir nesne almak için şöyle yaparız
ArrayList<Member> memberList = ...
Member member = memberList.get(ThreadLocalRandom.current().nextInt(memberList.size()));
nextLong metodu
Şöyle yaparız.
random.nextLong()

Hiç yorum yok:

Yorum Gönder