PDA

View Full Version : [Java] Synchronized vs Lock


spidey
20-07-2008, 19:11
Save a tutti.
Qualcuno può confermarmi che utilizzare l'una o l'altra modalità nel contesto seguente è del tutto equivalente?



public class Contatore{

int valore;

void synchronized incrementa(){valore++;}
void synchronized getValore(){System.out.println(valore);}

}




public class Contatore{

int valore;
Lock lock = new ReentrantLock();

void incrementa(){
try{
lock.lock();
valore++;}
finally{
lock.unlock();} }

void getValore(){
try{
lock.lock();
System.out.println(valore);
finally{
lock.unlock();}

}

banryu79
21-07-2008, 12:25
Leggendo la documentazione sembrerebbe di sì (cioè che l'uso della classe ReentrantLock e l'uso della keyword synchronized sono equivalenti nel tuo esempio):


public class ReentrantLock
extends Object
implements Lock, Serializable

A reentrant mutual exclusion Lock with the same basic behavior and semantics as the implicit monitor lock accessed using synchronized methods and statements, but with extended capabilities.



Una differenza, dal punto di vista prestazionale e non semantico, avrebbe potuto esserci se usavi la versione "fair" della classe, passando il booleano true al costruttore.
Cito sempre la documentazione:

The constructor for this class accepts an optional fairness parameter. When set true, under contention, locks favor granting access to the longest-waiting thread. Otherwise this lock does not guarantee any particular access order. Programs using fair locks accessed by many threads may display lower overall throughput (i.e., are slower; often much slower) than those using the default setting, but have smaller variances in times to obtain locks and guarantee lack of starvation.

La chiamata al costruttore senza parametri è equivalente alla chiamata al costruttore con parametri passando false.

ReentrantLock

public ReentrantLock()

Creates an instance of ReentrantLock. This is equivalent to using ReentrantLock(false).


Quindi dovresti stare a posto ;)

spidey
21-07-2008, 19:55
Ti ringrazio ;) Esaustivo come al solito :D