Featured post
java - Behaviour of threads with combination of synchronized methods in a class -
case 1
i have 2 synchronized methods shown below:
class { public void synchronized methoda() {} public void synchronized methodb() {} }
a: have threads t1 , t2. can threads simultaneously executemethoda
, methodb
(respectively) belonging same instance of class a?
- my analysis: answer no because 1 method executed thread t1 , thread t2 blocked until t1 finishes execution.
b: have threads t1 , t2. can threads simultaneously execute methoda
, methodb
(respectively) belonging different instances of class a?
- my analysis: answer yes because t1 , t2 can execute
methoda
,methodb
belonging different instances of class , not blocked.
is understanding correct per analysis case 1?
update: case 2
i have 2 synchronized methods, 1 non static , other static.
class { public void synchronized methoda() {} public void static synchronized methodb() {} }
a: have threads t1 , t2. can threads simultaneously execute methoda
, methodb
(respectively) belonging same instance of class a?
- my analysis: answer no because 1 method executed t1 , t2 blocked until t1 finishes execution.
b: have threads t1 , t2. can threads simultaneously execute methoda
, methodb
(respectively) belonging different instances of class a?
- my analysis: answer yes because t1 , t2 can execute
methoda
,methodb
belonging different instances , not blocked.
is understanding correct per analysis case 2?
case a: no
case b: yes
your analysis correct. synchronized keyword on instance method functionally equivalent this:
public void somemethod() { synchronized(this) { //code } }
since this
different in 2 contexts, not mutually exclusive. note same method called @ same time 2 different instances.
edit
for case 2, incorrect on 2a; doesn't make sense. static synchronized method not "belong" instance of class; if did wouldn't static! doesn't synchronize on any instance of class (it has no reference instance synchronize on!) instead synchronizes on class object of a
. static synchronized method in class a
equivalent this:
public static void methodb() { synchronized (a.class) { //code } }
your instance method synchronize on instance i've shown above, 2 threads can run in parallel.
in case b then, can run in parallel you're still missing fundamental concept static method not associated any instance.
- Get link
- X
- Other Apps
Comments
Post a Comment