multithreading - How does Java Synchronized compare locked objects? -


i want lock object on multiple api requests such 1 request per user can enter block of code.

does synchronized(obj) lock based on object's reference or hashcode() function?

i.e. do:

synchronized("asdf") {     dosomethingnifty(); } 

here "asdf" has unique hash no unique reference.

does synchronized(obj) lock based on object's memory location or tohash() function?

uh. neither? based on object's "reference" it's java identity jvm. not it's memory address because relocatable. not it's hash code (even in terms of object.hashcode()) because not unique.

in terms of should locking on, should same final object. like:

 private final object lockobject = new object(); 

you want final multiple threads can guaranteed locking on same object reference not changing.

here "asdf" has unique hash no unique memory address.

"asdf" not have unique hash since other strings might have same hash , may have unique reference if compiler smart caching of constant strings.

i.e. do:

it not idea lock on string way. if class locking on same string might or might not locking on same object may or may not want.

also, must never synchronize on mutable value non-final object boolean or integer. following pattern used , wrong:

   boolean value = false;    ...    synchronized (value) {       if (value) {          value = false;       } else {          value = true;       }    } 

this very wrong because value reference changing. 1 thread might lock on , change it's reference value thread lock on object , both threads within synchronized @ same time. worse because boolean there 2 values of true , false constants multiple classes locking on same references.


Comments

Popular posts from this blog

blackberry 10 - how to add multiple markers on the google map just by url? -

php - guestbook returning database data to flash -

delphi - Dynamic file type icon -