Showing posts with label Multithreading. Show all posts
Showing posts with label Multithreading. Show all posts

Wednesday, August 28, 2013

How synchronized methods can be ignored

Here is a question:

If an object has a synchronized method A and a not synchronized method B, can both method be called by different threads?

And the answer is:

Only one thread can access synchronized method A at a time (unless there are two different objects and each thread calls method A on different objects). B can be accesed by many threads at any given time, even when A is executing.

At the beginning I was a bit confused about the second part, if that is so, then a class might not be protected against multithreading update if it has at least one non-synchronized method that modifies an instance variable used by a synchronized method. I was right!

Here's is the code to prove it:

If you run this code it will sometimes show final value as 0 and other times value as 1. So when designing a class that should be synchronized take under consideration which methods are you leaving free that can modify instance (or static) attributes.
English Java Multithreading

 

Copyright © Librethinking.
Designed by Templateism. Hosted on Blogger Platform.