Using threads, I have a principal class (SlaveCrawler
) that instantiates three classes(Downloader, ContentAnalyzer, URLAnalyzer
) , which are dependent on each other.
SlaveCrawler
uses Downloader
and URLAnalyzer
Downloader
uses ContentAnalyzer
and URLAnalyzer
ContentAnalyzer
uses URLAnalyzer
I want only one instance of each class. If I use Singleton
, I can get this, but working with threads, I will have 20 SlaveCrawlers
(example), so I want 20 URLAnalyzer
.
It's possible make this using Singleton
or I need other way?
It can be used in a single threaded environment because multiple threads can break singleton property as they can access get instance method simultaneously and create multiple objects.
In a Singleton Object you have: Fields: They are stored in memory. They can be shared amongst multiple threads and you have no guarantee they will keep consistent (unless you make them synchronized).
Is singleton thread safe? A singleton class itself is not thread safe. Multiple threads can access the singleton same time and create multiple objects, violating the singleton concept. The singleton may also return a reference to a partially initialized object.
Thread Safe Singleton in JavaCreate the private constructor to avoid any new object creation with new operator. Declare a private static instance of the same class. Provide a public static method that will return the singleton class instance variable.
Take a look at ThreadLocal. Each thread will have its own local copy of each object.
ThreadLocal<YourObject> threadLocalYourObject = new ThreadLocal<YourObject>() {
@Override
protected YourObject initialValue() {
//initialize YourObject
}
}
Or in 1.8 we can use:
ThreadLocal<YourObject> threadLocalYourObject = ThreadLocal.withInitial( () -> new YourObject() )
To get access to your ThreadLocal object, use the get() method.
YourObject yourObject = threadLocalYourObject.get();
You can implement it with ThreadLocal. Here is the pseudo code:
public class ThreadLocalTest {
public static void main(String[] args){
MyTLSingleTon obj = MyTLSingleTon.getInstance();
}
}
class MyTLSingleTon{
private MyTLSingleTon(){
}
private static final ThreadLocal<MyTLSingleTon> _localStorage = new ThreadLocal<MyTLSingleTon>(){
protected MyTLSingleTon initialValue() {
return new MyTLSingleTon();
}
};
public static MyTLSingleTon getInstance(){
return _localStorage.get();
}
}
MyTLSingleTon.getInstance();
method will return an object assosiated with the current thread. and if no object is assosiated than protected MyTLSingleTon initialValue()
method will be called and a new instance will be set.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With