Search code examples
javaswingswingworkeropennlp

Java SwingWorker with same instance of Class?


I have a few SwingWorkers running and they all need OpenNLP for calculation. OpenNLP needs some time for initialisation so I wonder what's the best way doing this? I guess it's not smart to start one instance of OpenNLP in every SwingWorker. I could initialise one instance and passing it to every SwingWorker but the problem is that I can/want initalise OpenNLP only in the SwingWorkers and not before.

So I want to start all Workers in a loop and after start they (or just one of them?) should init die instance of OpenNLP. When it's ready every Worker should use it.

How can I do this?

Thanks!


Solution

  • Have all swing workers use a single factory bean that does synchronized lazy initialization:

    public class OpenNLPFactory {
    
      public synchronized OpenNLP getOpenNLP() {
          if(OpenNLP ready )  { 
              return it
          } else {
              build it and return it.
         }
      }
    
    }
    

    The OpenNLP object returned will itself have to be thread safe of course...