Java Question

In Java, it's possible Singleton per thread?

Using threads, I have a principal class (SlaveCrawler) that instantiates three classes(Downloader, ContentAnalyzer, URLAnalyzer) that 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?

Answer Source

Take a look at ThreadLocal. Each thread will have its own local copy of each object.

ThreadLocal<YourObject> threadLocalYourObject = new ThreadLocal<YourObject>() {
  protected YourObject initialValue() {
    //initialize YourObject

To get access to your ThreadLocal object, use the get() method.

YourObject yourObject = threadLocalYourObject.get();