java - Thread safe struts web app with spring -


in struts 2 , spring web based application, please consider below sample.

the bookmanager has action returns map of books client. map service layer injected spring

public class bookmanager extends actionsupport {     //with setter , getter    private map<string, bookvo> books;     @inject    bookservice bookservice     @action("book-form")    public string form(){            setbooks(bookservice.getallbooks());    }  } 

the service layer gets book list db returns map.

@named public class bookservice(){     private map<string,bookvo> books;     public map<string,bookvo> getallbooks(){        books = new hashmap<string,bookvo>();        //fill books db        return books;   }  } 

i have tested , found above implementation not thread safe.

  1. i can make code thread safe removing private field books bookservice , use method hashmap<string,bookvo>() books = new hashmap<string,bookvo>();. why change make code thread safe ?
  2. the struts action thread safe, shouldn't assure non thread safe spring service runs in thread safe manner.
  3. if use non thread safe version of service in action, making new service object instead of using spring inject, face no issue. why? if service not thread safe why making new instance , calling thread safe!

i can make code thread safe removing private field books bookservice , use method hashmap() books = new hashmap();. why change make code thread safe ?

because method-level variables thread safe, while class-level variables not.

the struts action thread safe, shouldn't assure non thread safe spring service runs in thread safe manner ?

nope. depends.

if use non thread safe version of service in action, making new service object instead of using spring inject, face no issue. why? if service not thread safe why making new instance , calling thread safe!

if instantiate manually in action, creating instance of object private action, thread-safe since actions threadlocal, , managed (that's means if bookservice class has @inject in it, container won't resolve them).

if instead have di managed container, instance not thread-safe; you're using (@inject, @named) more "spring", it's java ee, implementaton of jsr-330 (dependency injection) available in cdi-enabled applications (jsr-299).
cdi beans not thread safe. should use ejb3's @singleton thread-safe, don't need retain attribute @ class-level, since it's used returned, left there overwritten next time.

btw consider using reference cdi (weld in jboss) struts2 cdi-plugin, it's worthy of try.


Comments

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -