10

Traps for @Autowired and Threads

 3 years ago
source link: https://www.codesd.com/item/traps-for-autowired-and-threads.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Traps for @Autowired and Threads

advertisements

I wondering if I should exspect any problems when I autowire threads with prototype scope.

The thread:

...
@Service
@Scope("prototype")
public class MyThread extends Thread {
  ...
}

The thread starting class:

...
public class ThreadStarter {

  @Autowired
  private MyThread myThread;

  public void startThread(){
     myThread.start();
  }
}

The starting class will be called from a webservice implementation.

Are there any pitfalls I should take into consideration?


Well it reallty depends on what the thread class instance does.

Think of Servlet doGet and/or doPost methods. If you're being stateless and don't keep values in wider scopes (such as session or context) you're fine with not troubling yourself about which instance of your servlet will be called when. However if you are being statefull (get/put objects to the session scope for example) then you need to synchronize that servlet instance's access to said scope (synchronized(session)) or serialize the way requests are being treated by the servlet threads.

I think here you're pretty much in the same situation. You want to make your thread instance to be prototype scoped (and thus have a new instance created each time an injection is needed) if you are infact stateful and share data between your threads, and you can leave it to the default scope of singleton if that thread's run() method is stateless as far as data outside it is concerned.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK