Thursday, 15 July 2010

multithreading - Best practices for dealing with exceptions in a synchronized block/method in Java -



multithreading - Best practices for dealing with exceptions in a synchronized block/method in Java -

i have read must careful while coding synchronized blocks or methods because if thread exits synchronized method/block because of exception, synchronization lock released cause memory model couldn't care less whether thread exited because of exception. synchronization lock going available grabs other threads though object might in corrupted state.

so if consider best practices, there guidelines follow writing synchronized methods/blocks. think locks quite because of seek {} {} semantics if have api needs absolutely have synchronized methods/blocks, approach of coding these synchronized methods/blocks. thought might employ seek approach synchronized methods stringbuffer class not utilize approach. i'm not sure if of standard classes have synchronized methods utilize approach. should leaving logging part uncaughtexceptionhandler way out?

are there other practices come in handy? there way prevent other threads acquiring synchronization lock, should object's state corrupted. uncaughtexceptionhandlers , blocks can @ perform additional logging. right? can't prevent other threads subsequently acquiring synchronization lock. right? how should code synchronized methods/blocks in java?

critical sections (a.k.a., "synchronized blocks") can detrimental performance of application. larn amdahl's law. each time start write "synchronized," should inquire yourself, "can re-design eliminate need?"† if reply no, next question should be, "how can create little possible?"

if code in synchronized block can throw exception, not little possible. find way exception-throwing-thing without touching global state, , come in synchronized block modify state if exception-throwing-thing produced valid result.

if sounds asking write programme work, it's because am asking write programme work. message of amdahl's law have things in way less-than-optimal on uni-processor machine in order best performance multi-processor machine.

multi-processing has been around while, wide-spread deployment of multi-processing architectures new. people still using books written when "multi-processor" meant "supercomputer." of sudden, we've got laptops 4 , 8 cores, , cell phones have multiple cores.

it's time stop doing things old way.

† java.util.concurrent classes friends.

java multithreading synchronization

No comments:

Post a Comment