Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does 'synchronized' mean?

I have some questions regarding the usage and significance of the synchronized keyword.

  • What is the significance of the synchronized keyword?
  • When should methods be synchronized?
  • What does it mean programmatically and logically?
like image 931
Johanna Avatar asked Jul 06 '09 06:07

Johanna


People also ask

What do you mean by Synchronised?

Definition of synchronize intransitive verb. : to happen at the same time. transitive verb. 1 : to represent or arrange (events) to indicate coincidence or coexistence.

What does to sync mean?

Sync, short for "synchronize," is a verb for making things work together. When you lip-sync, you are moving your mouth to exactly match someone else's words spoken or sung at precisely the same time.

What does synchronized do in Java?

Synchronization in java is the capability to control the access of multiple threads to any shared resource. In the Multithreading concept, multiple threads try to access the shared resources at a time to produce inconsistent results. The synchronization is necessary for reliable communication between threads.


1 Answers

The synchronized keyword is all about different threads reading and writing to the same variables, objects and resources. This is not a trivial topic in Java, but here is a quote from Sun:

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.

In a very, very small nutshell: When you have two threads that are reading and writing to the same 'resource', say a variable named foo, you need to ensure that these threads access the variable in an atomic way. Without the synchronized keyword, your thread 1 may not see the change thread 2 made to foo, or worse, it may only be half changed. This would not be what you logically expect.

Again, this is a non-trivial topic in Java. To learn more, explore topics here on SO and the Interwebs about:

  • Concurrency
  • Java Memory Model

Keep exploring these topics until the name "Brian Goetz" becomes permanently associated with the term "concurrency" in your brain.

like image 148
Stu Thompson Avatar answered Oct 02 '22 06:10

Stu Thompson