Are Static methods Thread safe?

Hello All
I have a static method that takes a integer and returns a mathematically processed result.
Since this method is frequently required, I have placed it in a common class and declared it as static.
I want to know whether this method is thread safe?

There's nothing special about static methods, with regard to thread safety. If they access shared objects, then such access will usually need to be controlled by synchronisation; this might be on the object being accessed, some higher-level object or a special object allocated purely as a lock. The only way that you might think of them as special is that there's no instance of the Class on which you can synchronise.
You can declare a static method as synchronised. If you do, it will be synchronised on the single Class object of the class in which it is declared. This means that only one thread can be executing any part of the method at any one time. However, I understand that the Java Runtime itself sometimes synchronises on this Class object for its own reasons, therefore you might sometimes find a synchronised static method blocks when no other thread is executing it. Usually better, therefore, to explicitly synchronise on some object or other, than to use synchronised static methods.

Similar Messages

  • Are static objects thread safe?

    hi,
    i have seen code that looks like this:
    private static TestObject _to;
    static {
    _to = new TestObject();
    if methods within TestObject contain local variables, will local variables inside _to be threadsafe when hit by 2 requests?
    eg.
    User 1 makes a request to:
    _to.setStuff("abc");
    User 2 make a request to:
    _to.setStuff("def");
    Will User 1's now see "def" instead of "abc"?
    thanks
    - Edward Han
    [email protected]

    so what happens to the local variable holder? if 2
    people access the static variable _to and call
    setStuff() one right after the other, is there a
    chance that the first person in will print out what
    the second person in set as the holder?
    Local variables are thread specific and live on an execution stack, and each thread gets its own stack. If there are two threads, there are two stacks, and if both threads are "in" setstuff(), there are two distinct references called "holder" -- one per stack. And regardless of the order in which the threads enter that method, the references themselves are not clobbered. Now, what you see printed is an entirely different issue, as is the case if the "holder" references point to the same (shared) object.
    The key is this: a thread-specific resource is thread safe; a shared (unprotected and/or mutable) resource is not.

  • Are static methods in Java thread safe?

    Are static methods in Java thread safe?
    thanks,
    suresh

    if static method use the instance variable
    You mean member variable, where member variables are either class variables (static) or instance variables (non-static).
    then you have to make it thread safe using
    synchronization Not necessarily. Depends on requirements and usage context.
    else in case of local var. it
    is thread safe. Not necessarily. That local variable could refer to an object that's visible to multiple threads.
    Statements like "Local variables are threadsafe but member variables aren't" are an oversimplification.
    Something is threadsafe if it cannot be made to behave incorrectly simply by running it in a multithreaded context. Determining that can be very difficult.

  • Are WLE libraries thread safe?

    Hi,
    Can we implement multiple threads in c CORBA Servers. Are C libraries thread safe? Can i use pthread to create threads in WLE CORBA C servers
    regards,
    Manoj PG

    JSPs/Servlets are not threadsafe in that one instance of the class is created to handle all requests.
    But only your class attributes are not thread-safe. Local variables are stored for each invocation of the service method, and are thread safe.
    Basically you have to declare all your variables inside a method, and if you call any java methods, pass parameters.
    <%!
      int myNumber;   // class attribute - shared among all calls to this servlet
    %>
    <%
      int myLocalNumber; // local variable to method.  will be threadsafe
    %>In short, yes this code is threadsafe. The key will be the same when you get back from doing your "stuff".
    The only problem would be if two people hit it fast enough to get the same time, and thus the same key.
    Cheers,
    evnafets

  • Are the service(), doPost() and doGet() methods THREAD-SAFE?

    Please Let Me know If service(), doPost() and doGet() are Thread-safe. If they are not thread safe, How to make them thread-safe?

    Please Let Me know If service(), doPost() and doGet() are Thread-safe. They are not.
    If they are not thread safe, How to make them thread-safe?The best way is to avoid writing code that depends on a servlet's thread safety; i.e., no servlet instance variables - keep everything local to the method. Else, you'll want to learn about synchronization.
    [JavaWorld article - Write thread-safe servlets|http://www.javaworld.com/javaworld/jw-07-2004/jw-0712-threadsafe.html].
    ~

  • How are static methods handled in a multithreaded application?

    hi
    i have a class Drawer with a static method public static draw(Graphics g). now assume there are more thrads callin at the same time Drawer.draw(g). What happens? have some threads to wait until the others have finished calling the method, or can static methods be multithreaded, (can they perform simultaniously)?
    thanks, jo

    ups, i am not drawing on the screen, but in every thread i am drawing a Image. this means before i call the static method in every thread there will be created a BufferedImage and then i pass the Graphics from this images to the static method. also in this case the method performs simultaniously? every thread has its own image and graphics, so the static method should be perform at the same time, isn't it?

  • Is this method thread safe?

    Hi Guys
    I have the following code:
    public class MyClass extends HttpServlet {
         HttpSession session;
         public doGet(HttpServletRequest request, HttpServletResponse response)
                                      throws IOException, ServletException                              
              session = request.getSession(false);
              List<AClass> htransactions = (List<AClass>)session.getAttribute("AClass");
                   //do stuff here
    }What I want to know is that if the HttpSession session is declared as a instance variable, does this make it non thread safe? Or is using such a way of for a session fine?
    .

    Steve declared a thumb-rule.
    Bear Bibeault
    sheriff & author
    Member # 24697
    posted Yesterday 9:17 PM
    Yes, variables created inside methods are safe because each thread will get their own copies. Instance variables are unsafe because they are shared across all threads.
    Keep this in memory, hope this was a perfect clarification...you can declare now on the answer.

  • SingleThreadModel-static variables thread safe?

    Hi..
    I have one servlet which implements SingleThreadModel.My servlet contains two static variables .
    public class MyServlet extends HttpServlet
    implements SingleThreadModel {
    private static String firstName="Umar hathab";
    private static StringBuffer lastName= new StringBuffer("Abdullah");
    I want to know whether this two variables will be thread safe? I know that static vars are shared in JVM..
    Please help me..
    Thanks in advance..
    A.Umar

    Hi heyad..
    Static variables are shared among the instances.When we create two instances of an object which contains a static variable,both the instances share the same static variable.So there will be data corruption when two instances operate on the static variable at the same time.So I feel static variables are not thread safe.What I want to know is whether static variables are thread-safe when implemented by SingleThreadModel..
    A.Umar

  • Is ServletContext methods thread-safe?

    Just read servlet spec again, I know for shared data which is used by
              servlet must be thread-safe. But how about setAttribute/getAttribute methods
              on ServletContext and Session object? Are they thread-safe? or I have to
              synchronize the access to these methods?
              Any help is appreciated.
              

    hi Antalas,
    for Tomcat,it is not thread safe.but for WebSphere it is.for more info click on the following link :
    http://www.webagesolutions.com/knowledgebase/waskb/waskb026/index.html.
    [email protected]

  • Why are static methods called with null references,valid ?

    This is my code :
    package inheritance;
    public class inh6{
         public static void method(){
         System.out.println("Called");
         public static void main(String[] args){
              inh6 t4 = null;
         t4.method();
    O/P :
    CalledHere t4 is a null reference and yet we are able to call a method on it,why is null pointerexception not thrown.Why are we able to call static methods using null references ?
    t4 is null means it doesnot refer to any memeory address,hence how is method() called correctly.
    I hope i am clear. :)
    Thank you for your consideration.

    punter wrote:
    jverd wrote:
    Memory addresses have nothing to do with it. I doubt memory addresses are even mentioned once in the JLS.
    By memory address i mean the memory location the reference is pointing to.I know what you mean. But if you think it's relevant, can you show me where in the JLS it says anything about memory locations?
    >
    You can do that because a) t4's type is "reference to inh6" and b) method() is declared static, which means that you don't need an object to call it, just the class. That class comes from the compile time type of t4. The fact that t4 is null at runtime is irrelevant.
    So at compile time the type of t4 is inh6 and hence the method is called.Is it ? Had method() not been static a NullPointerException would have been thrown.Correct.
    With non-static, non-private, non-final methods, which implementation of the method gets called is determined at runtime, buy the class of the object on which it's being called. If any one of those "non"s goes away, then the method is entirely determined at compile time, and in the case of static methods, there's no instance necessary to call the method in the first place.

  • Are SocketFactory implementations thread-safe?

    Hi!
    I'm using a SSLSocketFactory-singleton (SSLSocketFactoryImpl it is I guess) for creating SSLSocket-instances in my application.
    I just wondered whether or not I need synchronization especially for using the createSocket(...)-methods in my multi-threaded application, since I can't look in the code due to restrictions. Another question is whether the answer applies to other SocketFactory implementations.
    Greetings

    georgemc wrote:
    JAVAnetic wrote:
    georgemc wrote:
    Why would you need SocketFactory to be thread-safe anyway?Because, in my multi-threaded application I want to use only one SocketFactory-instance to reduce the overhead of creating one per thread that needs Sockets. So this instance as a shared object used by many threads will need to be synchronized if it is not already thread-safe per se. But all you do with a SocketFactory is ask it for sockets. What issues do you think you'll face with multi-threaded requests for new instances of something? Just because you've got multi-threaded code, doesn't mean everything you use has to be synchronized.I know, but since I don't know what the factory-implementation actually does creating those instances I think it is always worth asking, if I have to synchronize even if it may be true that the design of (the) factory-implementation(s) is in fact thread-safe, which no one until now could tell me for sure.

  • Are page flows thread safe?

    Are pageflows thread safe? As in, can I have object level variables that
    don't need to be synchronized?
    Thanks

    Yes page flows are thread safe.

  • Are immutable objects thread safe

    I am having a debate with legosa as to if immutable objects are thread safe @
    http://forum.java.sun.com/thread.jsp?forum=37&thread=525250
    I would like the java gurus to put in their thoughts over here.

    I am having a debate with legosa as to if immutable
    objects are thread safe @
    http://forum.java.sun.com/thread.jsp?forum=37&thread=52
    250
    I would like the java gurus to put in their thoughts
    over here.There are some problems with the java memory model that can cause immutable objects to not be thread safe. This is discussed in the section Problem#1 in the following article from IBM:
    http://www-106.ibm.com/developerworks/library/j-jtp02244.html
    According to this article, some of the problems have been fixed in jdk1.4, while other fixes will have to wait until jdk1.5.

  • Are i++, i-- atomic and thread safe for int i

    I want to minimize the sync time multiple threads take to contend for a shared pool, which is implemented as a FIFO. My plan is to:
    1. Use a int variable "count" to trace the free obj count. Hence eliminates the need of synchonized methods size() and isEmpty()
    2. Increment & decrement count when implemeting push() and pop()
    3. Minimize the number of statements in synchonized block as possible within push() and pop(), which in this case, excludes count++ and count-- provided these operations are atomic and thread safe
    Have I lost something ?

    So, may I make a conclusion.
    To minimize contention, I use FIFO instead LIFO or stack and build it from scratch without extending from existing Collection-related class
    1 public class FIFO {
    2 . . private volatile int count;
    3 . . private Object head, tail;
    4 . . public Object pop() {
    5 . . . .synchonized (tail) {
    6 . . . . .if (count >= 3) {
    7 . . . . . .Object tail_origin = tail;
    8 . . . . . .// Re-organizing the linked list skipped
    9 . . . . . .synchonized (this) {
    10 . . . . . . count--;
    11 . . . . . }
    12 . . . . . return tail_origin;
    13 . . . . }
    14 . . . . else {
    15 . . . . . throw new PoolEmptyException();
    16 . . . . }
    17 . . . }
    18 . . }
    19 . . public void push(Object o) {
    20 . . . synchronized (head) {
    21 . . . . . // Re-organizing the linked list skipped
    22 . . . . . head = o;
    23 . . . . . synchonized (this) {
    24 . . . . . . count++;
    25 . . . . . }
    26 . . . }
    27 . . }
    28 . . public int sizeOf() {
    29 . . . return count;
    30 . . }
    31 }
    1. The reason I choose FIFO is to avoid the contention between push() and pop() -- they are NOT declared as synchonized, instead they only lock head and tail respectively. (Sorry I borrow the name push and pop from stack)
    2. pop() only works when count >= 3 to avoid head == tail after pop() and hence a further call to push() block concurrent call to pop() and vice versa (see line 5 and 20)
    3. The goal is to minimize the time and scope of contention. In line 9 and 23, I lock the whole pool object only when modify count, which is not atomic.
    4. This pool is used for a thread pool supporting many concurrent short-lived HTTP request
    Have I missed something ?
    Thanks a lot!

  • Use of Synchronised with Static methods in EJBs

    We have a number of classes whose static methods are called by multiple EJBs. Could you tell me whether I might need to Synchronise these static methods or will this be unnecessary because they are being called by an EJB for a specific user.
    Thanks
    Dave

    Whether or not a method (static or non-static) is thread-safe depends on whether or not the method accesses instance and/or class variables or only method-local variables...
    dave horner wrote:
    We have a number of classes whose static methods are called by multiple EJBs. Could you tell me whether I might need to Synchronise these static methods or will this be unnecessary because they are being called by an EJB for a specific user.
    Thanks
    Dave

Maybe you are looking for