You are on page 1of 23

Inter-thread communication

Polling
• The process of testing a condition repeatedly till it
becomes true is known as polling.
• Polling is usually implemented with the help of loops
– to check whether a particular condition is true or not.
– If it is true, certain action is taken.
– This waste many CPU cycles and makes the implementation
inefficient.
– For example, in a classic queuing problem where one thread is
producing data and other is consuming it.
Avoid polling
• Java uses three methods, namely, wait(), notify() and
notifyAll().
• All these methods belong to object class as final so that all
classes have them.
• They must be used within a synchronized block only.
– wait()- tells the calling thread to give up the lock and go to sleep
until some other thread enters the same monitor and calls notify().
– notify()- wakes up one single thread that called wait() on the same
object. It should be noted that calling notify() does not actually give
up a lock on a resource.
– notifyAll()- wakes up all the threads that called wait() on the same
object.
class Q { caught");
int n; }
boolean valueSet = false; this.n = n;
synchronized int get() { valueSet = true;
while(!valueSet) System.out.println("Put: " + n);
try { notify();
wait(); }}
} catch(InterruptedException e) {
System.out.println("InterruptedException
caught"); class Producer implements Runnable {
} Q q;
System.out.println("Got: " + n); Producer(Q q) {
valueSet = false; this.q = q;
notify(); new Thread(this, "Producer").start(); }
return n; } public void run() {
synchronized void put(int n) {while(valueSet) int i = 0;
try { wait(); while(true) {
} catch(InterruptedException e) { q.put(i++);
System.out.println("InterruptedException }}}
class Consumer implements Runnable {
Q q;
Consumer(Q q) {
this.q = q;
new Thread(this, "Consumer").start();
}
public void run() {
while(true) {
q.get();
}}}
class threadexample{
Put: 1
public static void main(String args[]) { Got: 1
Q q = new Q(); Put: 2
new Producer(q); Got: 2
new Consumer(q); Put: 3
System.out.println("Press Control-C to stop."); Got: 3
Put: 4
}
Got: 4
} Put: 5
Got: 5
Deadlock
• A special type of error - need to avoid that relates
specifically to multitasking is deadlock,
• occurs when two threads have a circular dependency
on a pair of synchronized objects.
• suppose one thread enters the monitor on object X
and another thread enters the monitor on object Y.
• If the thread in X tries to call any synchronized
method on Y, it will block as expected.
• However, if the thread in Y, in turn, tries to call any
synchronized method on X, the thread waits
forever, because to access X, it would have to
release its own lock on Y so that the first thread
could complete
• Deadlock is a difficult error to debug for two
reasons:
– it occurs only rarely, when the two threads time-
slice in just the right way.
– It may involve more than two threads and two
synchronized objects
class A {
synchronized void foo(B b) {
String name = Thread.currentThread().getName();
System.out.println(name + " entered A.foo");
try {
Thread.sleep(1000);
} catch(Exception e) {
System.out.println("A Interrupted");
}
System.out.println(name + " trying to call B.last()");
b.last();
}
synchronized void last() {
System.out.println("Inside A.last");
} MainThread entered A.foo
} RacingThread entered B.bar
MainThread trying to call B.last()
RacingThread trying to call A.last()
class B {
synchronized void bar(A a) {
String name = Thread.currentThread().getName();
System.out.println(name + " entered B.bar");
try {
Thread.sleep(1000);
} catch(Exception e) {
System.out.println("B Interrupted");
}
System.out.println(name + " trying to call A.last()");
a.last();
}
synchronized void last() {
System.out.println("Inside A.last");
} MainThread entered A.foo
} RacingThread entered B.bar
MainThread trying to call B.last()
RacingThread trying to call A.last()
class Deadlock implements Runnable {
A a = new A();
B b = new B();
Deadlock() {
Thread.currentThread().setName("MainThread");
Thread t = new Thread(this, "RacingThread");
t.start();
a.foo(b); // get lock on a in this thread.
System.out.println("Back in main thread");
}
public void run() {
b.bar(a); // get lock on b in other thread.
System.out.println("Back in other thread");
}
public static void main(String args[]) {
new Deadlock();
} MainThread entered A.foo
} RacingThread entered B.bar
MainThread trying to call B.last()
RacingThread trying to call A.last()
• Avoid Dead Lock condition
• We can avoid dead lock condition by knowing its possibilities. It’s a very
complex process and not easy to catch. But still if we try, we can avoid
this. There are some methods by which we can avoid this condition. We
can’t completely remove its possibility but we can reduce.
• Avoid Nested Locks : This is the main reason for dead lock. Dead Lock
mainly happens when we give locks to multiple threads. Avoid giving lock
to multiple threads if we already have given to one.
• Avoid Unnecessary Locks : We should have lock only those members
which are required. Having lock on unnecessarily can lead to dead lock.
• Using thread join : Dead lock condition appears when one thread is
waiting other to finish. If this condition occurs we can use Thread.join
with maximum time you think the execution will take.
• Important Points :
• If threads are waiting for each other to finish,
then the condition is known as Deadlock.
• Deadlock condition is a complex condition which
occurs only in case of multiple threads.
• Deadlock condition can break our code at run
time and can destroy business logic.
• We should avoid this condition as much as we
can.
Composition
• Inheritance is only when classes are in a relationship in
which subclass is a (kind of) superclass.
• For eg: A Car is a Vehicle so the class Car has all the features
of class Vehicle in addition to the features of its own class.
• we cannot always have is a relationship between objects of
different classes.
• For eg: A car is not a kind of engine. To represent such a
relationship, we have an alternative to inheritance known
as composition.
• It is applied when classes are in a relationship in which
subclass has a (part of) superclass.
• inheritance - subclass extends the
functionality of a superclass,
• Composition - a class reuses the functionality
by creating a reference to the object of the
class it wants to reuse.
– For eg: A car has an engine, a window has a
button, a zoo has a tiger.
class Date
{
private int day;
private int month;
private int year;
Date(int dd, int mm,int yy)
{
System.out.println("Constructor of Data Class is Called");
day=dd;
month=mm;
year=yy;
}
public String toString()
{
return (day+"/"+month+"/"+year);
}
}
class Employee
{ private int id;
private String name;
private Date hireDate; //object of Data class
Employee(int num,String n, Date hire)
{ System.out.println("Constructor of Employee Class is Called");
id=num ;
name=n ;
hireDate=hire; }
public void display()
{ System.out.println("id = "+id);
System.out.println("Name = "+name);
System.out.println("Hiredate = "+hireDate); } }
public class Composition
{ public static void main(String[] args)
{ Date d = new Date(01,01,2011);
Employee emp = new Employee(1,"Dinesh Thakur",d);
emp.display(); } }
import java.applet.Applet;import java.awt.Graphics;
import java.util.Calendar;
public class NewApplet extends Applet implements Runnable{
String msg=""; Thread t=null;
public void run()
{for(;;) {
Calendar c=Calendar.getInstance();
msg=c.get(Calendar.HOUR)+":"+c.get(Calendar.MINUTE)
+":"+c.get(Calendar.SECOND);
try {repaint(); t.sleep(500); }
catch(InterruptedException e)
{ } }}
public void init() {
t=new Thread(this); t.start(); }
public void paint(Graphics g)
{ g.drawString(msg,50,50); }}
import java.awt.*;
import java.applet.*;
/*
<applet code="StatusWindow" width=300 height=50>
</applet>
*/
public class StatusWindow extends Applet {
public void init() {
setBackground(Color.cyan);
}
// Display msg in applet window.
public void paint(Graphics g) {
g.drawString("This is in the applet window.", 10, 20);
showStatus("This is shown in the status window.");
}
}
< APPLET
[CODEBASE = codebaseURL]
CODE = appletFile
[ALT = alternateText]
[NAME = appletInstanceName]
WIDTH = pixels HEIGHT = pixels
[ALIGN = alignment ]
[VSPACE = pixels] [HSPACE = pixels]
>
[< PARAM NAME = AttributeName VALUE = AttributeValue>]
[< PARAM NAME = AttributeName2 VALUE = AttributeValue>]
...
[HTML Displayed in the absence of Java]
</APPLET>
// Use Parameters fontSize = Integer.parseInt(param);
import java.awt.*; import java.applet.*; else
/* fontSize = 0; } catch(NumberFormatException e) {
<applet code="ParamDemo" width=300 fontSize = -1; }
height=80> param = getParameter("leading");
<param name=fontName value=Courier> try { if(param != null)
<param name=fontSize value=14> leading = Float.valueOf(param).floatValue();
<param name=leading value=2> else
<param name=accountEnabled value=true> leading = 0;} catch(NumberFormatException e) {
</applet> leading = -1; }
*/ param = getParameter("accountEnabled");
public class ParamDemo extends Applet { if(param != null)
String fontName; int fontSize; active = Boolean.valueOf(param).booleanValue(); }
float leading; boolean active; // Display parameters.
// Initialize the string to be displayed. public void paint(Graphics g) {
public void start() { g.drawString("Font name: " + fontName, 0, 10);
String param; g.drawString("Font size: " + fontSize, 0, 26);
fontName = getParameter("fontName"); g.drawString("Leading: " + leading, 0, 42);
if(fontName == null) g.drawString("Account Active: " + active, 0, 58);
fontName = "Not Found"; }}
param = getParameter("fontSize");
try { if(param != null)
public void paint(Graphics g) {
String msg;
URL url = getCodeBase(); // get code base
msg = "Code base: " + url.toString();
g.drawString(msg, 10, 20);
url = getDocumentBase(); // get document base
msg = "Document base: " + url.toString();
g.drawString(msg, 10, 40);
• To actually load another file showDocument( ) method defined by the
AppletContext interface
– Applet getApplet(String appletName) Returns the applet specified by
appletName if it is within the current applet context. Otherwise, null is
returned.
– Enumeration<Applet> getApplets( ) Returns an enumeration that contains all
of the applets within the current applet context.
– AudioClip getAudioClip(URL url) Returns an AudioClip object that encapsulates
the audio clip found at the location specified by url.
– Image getImage(URL url) Returns an Image object that encapsulates the image
found at the location specified by url.
• The AudioClip interface defines these methods:
– play( ) (play a clip from the beginning),
– stop( ) (stop playing the clip), and
– loop( ) (play the loop continuously).
– Load an audio clip using getAudioClip( )
• The AppletStub interface provides the means by which an applet and the browser
(or applet viewer) communicate. Code will not typically implement this interface.

You might also like