Thread security

Security problem in java web

In tradition web develop, Servlet implement response to http request.
Servlet is one of the important standard of J2EE, it set how java response to Http request.
In project, classpath need relay on servlet-api.jar of j2ee.jar.
We can interact with web container through HttpServletRequest and HttpServletResponse object.

When container receive a request, container will dispatch a thread that
define in advance from main thread(tomcat observer pattern), to deal the mapping servlet implement.
When another request come in, main thread will choose thread from threadpool to serve,
but it do not care is there other threads using this implement.

So web container use singleton pattern to implement service object.
This pattern can reduce the servlet space waste, and improve response performance.
But it lead to security problem, the servlet in container is not thread security save.

HashMap and HashTable

  • HashMap implement Map interface from java 1.2
  • a light weight implement of HashTable, no contains method(avoid confusion)
  • All key / value in HaspMap entry are object(can be null).
  • not security save

  • HashTable is security save, it’s method is Synchronized

  • HashTable & HashMap hash implement is same, so performance in Synchronized is same too.

Theory

if multi-thread program run in same code result is same with single thread expect,
then thread secure. Thread security is caused by global or static changeable variable.
If only read operation on these variable in program, then no thread security problem in regular.

Thread security

In multi-thread environment, a class execute method, obtain independent resource

  • method signature variable is save(???)
  • local variable in method is save

ThreadLocal

ThreadLocal is self is not a thread, it’s static class.
It maintain thread’s independent copy ThreadLocalMap.

one side: all thread visit it’s own ThreadLocalMap
another side: one thread visit it’s own ThreadLocal

Summary

  • ThreadLocal maintain thread’s variable, to deal visit conflict.
  • Synchronized use JVM lock mechanism to make sure resource atomicity(one thread visit in time).

ThreadLocal use space to exchange time, provide every thread a variable copy, make sure visit concurrent but no conflict.
Synchronized use time to exchange space, monitor a target, to make thread visit in queue.

http://blog.51cto.com/dongisland/1369375