troubleshooting Question

Why is getter method required to be synchronized for the class to be Thread Safe

Avatar of Rohit Bajaj
Rohit BajajFlag for India asked on
Java
11 Comments3 Solutions97 ViewsLast Modified:
Hi,
Here is an example from java concurrency in practice making a class Thread Safe.


Screen-Shot-2019-03-11-at-6.27.15-PM.pngI want to understand the following in it -
1) Why is synchronized required on get method ?
Logically it looks like if any time set is called since its synchronized so the
value variable should also be visible to other threads. The latest updated value.

Then why is the get method required to be synchronized ?
Any example where thread safety might break if we dont synchronize get method ?

2) Whats the use of @GuardedBy annotation is it mandatory or optional ?
Is it just a marker thing to tell that its access is inside synchronized method ??

Thanks
ASKER CERTIFIED SOLUTION
ste5an
Senior Developer

Our community of experts have been thoroughly vetted for their expertise and industry experience.

Join our community to see this answer!
Unlock 3 Answers and 11 Comments.
Start Free Trial
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 3 Answers and 11 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros