android - Java synchronized method -


consider code:

public synchronized void onsignalstimeout(list<signalspec> specs) {     if (specs != null && specs.size() > 0) {         (signalspec spec : specs) {             parsedcansignal timeoutedsignal = new parsedcansignal();             signalsprovider.getinstance().setsignal(spec.name, spec.parent.parent.channel, timeoutedsignal);         }     } } 

i've got simple question: when thread 1 calls onsignalstimeout method, can thread 2 access objects accessed in method?

can't find anywhere if 'synchronized' locks access method or access objects used in method.

first of all, forget synchronized methods. so-called synchronized method...

synchronized anytype foobar(...) {     dosomething(); } 

is nothing shortcut way of writing this:

anytype foobar(...) {     synchronized(this) {         dosomething();     } } 

there nothing special method in either case. special synchronized block, , synchronized block simple. when jvm executes this:

synchronized(foo) {     dosomething(); } 

it first evaluates expression foo. result must object reference. locks object, performs body of synchronized block, , unlocks object.

but locked mean? may mean less think. not prevent other threads using object. doesn't prevent them accessing object's fields or, updating fields. thing locking object prevents is, prevents other threads locking same object @ same time.

if thread tries enter synchronized(foo) {...} while thread b has foo locked (either in same synchronized block, or in different one), thread forced wait until thread b releases lock.


you use synchronized blocks protect data.

suppose program has collection of objects can in different states. suppose states make sense, there other states don't make sense—invalid states.

suppose not possible thread change data 1 valid state valid state without temporarily creating invalid state.

if put code changes state in synchronized(foo) block, , put every block of code can see state synchronized block locks same object, foo, prevent other threads seeing temporary invalid state.


Comments

Popular posts from this blog

yii2 - Yii 2 Running a Cron in the basic template -

asp.net - 'System.Web.HttpContext' does not contain a definition for 'GetOwinContext' Mystery -

mercurial graft feature, can it copy? -