This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
resolving the following drag&drop question, I came accross a strange thing, synchronizing code with System.out, instead of MyClass.class or this:
In order to make sure that my assertions concerning two things are correct, here my questions:
1) Is synchronized(System.out) equivalent to synchronized(MyClass.class)? As far, as I know, "System.out” is a static PrintStream object, isn't it?
2) What about the volatile keyword? I suppose it guarantees that both threads are informed when the variable x changes, is this correct?
(I mean communication between both threads, as each thread in Java takes place in a separate memory space)
In any case, I did this exercise wrong only because I've dragged new String("xy") instead of System.out into the synchronization expression ... but I've survived it ;-))
1) You can compare synchronized(System.out) and synchronized(MyClass.class). Both will synchronize on an object which has a single copy in a JVM so only one thread can enter such a synchronized block at a time.
2) Volatile keyword is used with variables whose values change frequently. This makes sure that threads don't cache a local copy of the variable so that the thread uses the actual value of the variable at runtime not a cached value...
Thank you, guys - your explanations have helped me a lot in order to see the thread issues much clearer!
Besides, ExamLab is a very good testing tool, thank you Deepak:
althoug it's hard to do these mocks (besides, a lot of review work has to be done after each test unit), it's worth ... hopefully, the real exam will be "a piece of cake" compared with ExamLab ;-)