27.10.2014 Views

Cracking the Coding Interview, 4 Edition - 150 Programming Interview Questions and Solutions

Cracking the Coding Interview, 4 Edition - 150 Programming Interview Questions and Solutions

Cracking the Coding Interview, 4 Edition - 150 Programming Interview Questions and Solutions

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

<strong>Solutions</strong> to Chapter 18 | Threads <strong>and</strong> Locks<br />

18.6 You are given a class with synchronized method A, <strong>and</strong> a normal method C. If you<br />

have two threads in one instance of a program, can <strong>the</strong>y call A at <strong>the</strong> same time? Can<br />

<strong>the</strong>y call A <strong>and</strong> C at <strong>the</strong> same time?<br />

SOLUTION<br />

pg 86<br />

Java provides two ways to achieve synchronization: synchronized method <strong>and</strong> synchronized<br />

statement.<br />

Synchronized method: Methods of a class which need to be synchronized are declared with<br />

“synchronized” keyword. If one thread is executing a synchronized method, all o<strong>the</strong>r threads<br />

which want to execute any of <strong>the</strong> synchronized methods on <strong>the</strong> same objects get blocked.<br />

Syntax: method1 <strong>and</strong> method2 need to be synchronized<br />

1 public class SynchronizedMethod {<br />

2 // Variables declaration<br />

3 public synchronized returntype Method1() {<br />

4 // Statements<br />

5 }<br />

6 public synchronized returntype method2() {<br />

7 // Statements<br />

8 }<br />

9 // O<strong>the</strong>r methods<br />

10 }<br />

Synchronized statement: It provides <strong>the</strong> synchronization for a group of statements ra<strong>the</strong>r<br />

than a method as a whole. It needs to provide <strong>the</strong> object on which <strong>the</strong>se synchronized statements<br />

will be applied, unlike in a synchronized method.<br />

Syntax: synchronized statements on “this” object<br />

1 synchronized(this) {<br />

2 /* statement 1<br />

3 * ...<br />

4 * statement N */<br />

5 }<br />

i) If you have two threads in one instance of a program, can <strong>the</strong>y call A at <strong>the</strong> same time?<br />

Not possible; read <strong>the</strong> above paragraph.<br />

ii) Can <strong>the</strong>y call A <strong>and</strong> C at <strong>the</strong> same time?<br />

Yes. Only methods of <strong>the</strong> same object which are declared with <strong>the</strong> keyword synchronized<br />

can’t be interleaved.<br />

CareerCup.com<br />

2 6 4

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!