Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Thread - Synchronization issue

From Sun's tutorial:

Synchronized methods enable a simple strategy for preventing thread interference and memory consistency errors: if an object is visible to more than one thread, all reads or writes to that object's variables are done through synchronized methods. (An important exception: final fields, which cannot be modified after the object is constructed, can be safely read through non-synchronized methods, once the object is constructed) This strategy is effective, but can present problems with liveness, as we'll see later in this lesson.

Q1. Is the above statements mean that if an object of a class is going to be shared among multiple threads, then all instance methods of that class (except getters of final fields) should be made synchronized, since instance methods process instance variables?

like image 323
Yatendra Avatar asked Jul 31 '26 06:07

Yatendra


1 Answers

In order to understand concurrency in Java, I recommend the invaluable Java Concurrency in Practice.

In response to your specific question, although synchronizing all methods is a quick-and-dirty way to accomplish thread safety, it does not scale well at all. Consider the much maligned Vector class. Every method is synchronized, and it works terribly, because iteration is still not thread safe.

like image 66
Yishai Avatar answered Aug 01 '26 20:08

Yishai



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!