25.03.2013 Views

Cracking the Coding Interview - Fooo

Cracking the Coding Interview - Fooo

Cracking the Coding Interview - Fooo

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

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

18 6 You are given a class with synchronized method A, and 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 and C at <strong>the</strong> same time?<br />

SOLUTION<br />

CareerCup com<br />

pg 86<br />

Java provides two ways to achieve synchronization: synchronized method and 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 and 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 and 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 />

2 6 4

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

Saved successfully!

Ooh no, something went wrong!