• Post Reply Bookmark Topic Watch Topic
  • New Topic

One basic thread question

 
zack ma
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Does JVM gurantee operator ++ or -- thread safe?

Thanks!
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24213
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No.
 
Mr. C Lamont Gilbert
Ranch Hand
Posts: 1170
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
depends upon the variable. longs and doubles no, everything else I believe the answer is yes. And for longs and doubles declare them as volatile, and your ok.

It may also depend upon what you mean by thread safe? If by that you mean atomic, then we are on the same page.
 
David Harkness
Ranch Hand
Posts: 1646
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by CL Gilbert:
longs and doubles no, everything else I believe the answer is yes.

What I know for certain is that longs and doubles are not guaranteed to have write-atomicity: you may read half of the new value and half of the old value. The others do have write-atomicity.

Since increment and decrement are a read-and-write operation, I can't say for certain whether they are threadsafe. What you are guaranteed of is that you'll either get the whole old or new value. Of course, if two increment operations get split, you'd end up with only a single increment.
 
Mr. C Lamont Gilbert
Ranch Hand
Posts: 1170
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
good point. The ++ and -- operations are not atomic.
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24213
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hence, as I said, no.
 
Mr. C Lamont Gilbert
Ranch Hand
Posts: 1170
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Ernest Friedman-Hill:
Hence, as I said, no.


Sorry, I get paid by the word
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!