Techie Hints

A place where to find tech solution

Most Likely Interview Question What is Race Condition ?

 

Race conditions occurs when two thread operate on same object without proper synchronization and there operation interleaves on each other.

Example:

public Singleton getInstance(){

if(_instance == null){   //race condition if two threads sees _instance= null

_instance = new Singleton();

}

}

 

an easy way to fix “check and act” race conditions is to synchronized keyword and enforce locking which will make this operation atomic and guarantees that block or method will only be executed by one thread and result of operation will be visible to all threads once synchronized blocks completed or thread exited form synchronized block.

Way to handle race.

public Singleton synchronized getInstance(){

if(_instance == null){   //race condition if two threads sees _instance= null

_instance = new Singleton();

}

}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: