views:

75

answers:

4

Hello,

I'm writing my Servlet application and would like to use the following static method which will multiply x and y.

public class Helper {
    private Helper() {
        throw new AssertError();
    }

    public static int mutltiply(int a, int b) {
        int c = a*b;
        return c;
    }
 }

I understand that Servlets are multi threading environment. Is it safe to call such method from the servlet?

should I add synchronize property to this function? My concert is regarding value of c variable under multi threading.

I'm new in Java so this information would be very helpful.

Danny.

+2  A: 

c is a local variable so this method is reentrant and thread safe. You can safely use it from multiple threads.

Darin Dimitrov
+1  A: 

Yes, that method is thread safe. As long as you only use local variables you will be thread safe.

Skip Head
+1  A: 

As long as you don't use static fields, I see no problems. But if you're really creating a method which multiply, maybe you need to rethink some parts of your application.

Colin Hebert
You are absolutely right :) this is the first action that came into my mind :)
danny.lesnik
+2  A: 

Your static method is stateless. As it's not referring to anything outside of the method scope this would be safe anywhere.

That being said, consider splitting out generic functionality like this into another class. It's better for classes to follow the single responsibility principle, and you'll be able to use your static methods in other servlets.

Steve B.