Beware of unsafe variables (Servlets/JSP/Restlets)

Recently in my poject i was writing a restlet(very similar to sevlet/jsp). I wrote the code in a normal javabean style.
I declared few static variables. I was happy that i did the job nicely. But when code review happened i found out that the code was not Thread safe.

These Local variables were killing the code as they are not Thread safe. Two threads can the value of these variables simultanously and can harm the product. There are ways to make this code thread safe.

  1. Synchronize the code using Synchronized block or method.
  2. Use Single Threaded Model (Not recommended)

My code was –>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class ABC extends Resource {
 
Logger log = Logger.getLogger(ABC.class);
 
private static int maxNumber;   /* THESE TWO VARIABLES RENDERING MY CODE THREAD UNSAFE */
private static int userName;
 
public ABC(Context context, Request request,
Response response) {
super(context, request, response);
getVariants().add(new Variant(MediaType.TEXT_XML));
}
 
}

How would you make this code thread safe ??

This entry was posted in JAVA and tagged . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*