1

With respect to this question, I have a sub question

Are non-synchronised static methods thread safe if they don't modify static class variables?

If I have this method defined in a Singleton class

public static Date getDateDiff(Date a, Date b){ return a-b; } 

If two threads simultaneously concurrently call this method and pass different a,b then will they get correct results?

My understanding is they should get since each is passing different date object which is not accessible to the other ...

Under which condition will they get wrong results due to overwriting of the Date objects?

5
  • 1
    What, in your mind, is the difference between the linked question and yours? I don't see any. Commented Jul 24, 2014 at 14:17
  • @usr One difference is that the parameters passed in his question are mutable. Commented Jul 24, 2014 at 14:18
  • 1
    Tomasz' answer to the linked question answers this, if the passed-in objects are mutable then other threads can be tampering with them concurrently. i don't see how this question differs from the linked one. Commented Jul 24, 2014 at 14:18
  • possible duplicate of Are non-synchronised static methods thread safe if they don't modify static class variables? Commented Jul 24, 2014 at 14:21
  • actually i did not find the answer in that question, so i decided to be more simple and specific ... apart from could help some others Commented Jul 26, 2014 at 13:02

1 Answer 1

1

Yes, the two threads will get a correct result. The condition of an incorrect result would be if there is any other non-thread-safe code where another thread could be modifying a or b that's being passed by one of the other threads. Just like the other answer in the question you link to, if a or b is being shared with another thread, and they modify it while another thread is using it, you could run into problems.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.