Title: Threads, Garbage Collection, and Memory
1Java Programming
- CHAPTER 14,17
- Threads, Garbage Collection, and Memory
2Contents
- Creating Threads
- Using Runnable
- Synchronization
- Wait, notifyAll, and notify
- Thread Scheduling
- Deadlocks
- Garbage Collection
- A Simple Model of Finalization
- Interacting with the Garbage Collector
3A Scenario for Threads
- A thread is called a sequence of steps executed
on at a time. - The single threaded programming model is the one
most programmers use. The multithreading is
called the analogue to having multiple real-world
bank tellers.
bal a.getBalance()
bal b.getBalance()
bal deposit
bal deposit
a.setBalance(bal)
b.setBalance(bal)
a is a thread object of some bank
b is a thread object of another bank
4An Overview of Threads
- What is a Thread?
- A sequence of execution within a process
- A Lightweight process
- JVM manages and schedules threads
- Possible States
- (1) new (2) ready (3) running (4) waiting (5)
dead
5An Overview of Threads
Dead
Sleep,wait,I/O
Running
Waiting
Ready
New
6Creating Threads
- Creating a Thread Object
- Thread worker new Thread()
- Two ways
- Using the Thread Class
- Using the Runnable interface
- Using the Thread Class
- public class PingPong extends Thread
- private String word
- private int delay
- public PingPong(String whatToSay, int delayTime)
- word whatToSay
- delay delayTime
-
- public void run()
- try
- for()
- System.out.print(word )
- Thread.sleep(delay)
-
- catch (InterruptedException e)
- return
-
-
- public static void main(String args)
- new PingPong(ping, 33).start()
Extend the Thread class
Implement the run method
7Using Runnable
- Using Runnable
- Create a Thread object to pass object of
implementation of the Runnable interface into
Thread Constructor. - Be useful when used with other application such
as GUI or applet..
- public class RunPingPong implements Runnable
- private String word
- private int delay
- public PingPong(String whatToSay, int delayTime)
- word whatToSay
- delay delayTime
-
- public void run()
- try
- for()
- System.out.print(word )
- Thread.sleep(delay)
-
- catch (InterruptedException e)
- return
-
-
- public static void main(String args)
- Runnable ping new RunPingPong(ping, 33)
Implement Runnable Interface
Implement the run method
Create Thread object
8Using Runnable
- Printer Server Example
- class PrintServer implements Runnable
- private final PrintQueue requests new
PrintQueue() - public PrintSever()
- new Thread(this).start()
-
- public void print(PrintJob job)
- requests.add(job)
-
- public void run()
- for() realPrint(requests.remove())
-
- private void realPrint(PrintJob job)
- // do the real work of printing
-
- Other Version
- class PrintServer2
- private final PrintQueue requests new
PrintQueue() - public PrintSever2()
- Runnable service new Runnable()
- public void run()
- for() realPrint(requests.remove())
-
-
- new Thread(service).start()
-
- public void print(PrintJob job)
- requests.add(job)
-
- private void realPrint(PrintJob job)
- // do the real work of printing
-
-
9Synchronization
- Synchronized Methods protection from
interference in a multithreaded environment
acquire lock
wait to acquire lock
synchronized method
release lock
acquire lock
synchronized method
release lock
If one thread invokes a synchronized method on an
object, the lock of that object is first
acquired, the method body executed, and then the
lock released. Another thread invoking a
synchronized method on that same object will
block until the lock is released
10Locking Objects with Synchronized Methods
1
4
2
5
3
6
OK. method1() Not busy
No! Not while method2() for obj1 is executing
OK. method2() Not busy
No! Not while method1() for obj2 is executing
Always OK.
Always OK.
11Synchronized Methods
- Example Code
- public class BankAccount
- private long number // account number
- private long balance // current balance (in
cents) - public BankAccount(long initialDeposit)
- balance initialDeposit
-
- synchronized public long getBalance()
- return balance
-
- private final void setBalance(double amount)
- balance amount
-
- synchronized public void deposit(double amount)
- double bal getBalance()
- bal amount
- setBalance(bal)
-
- // rest of methods
Example Refer to the TellerTest.java
12Static synchronized Methods
- Static synchronized Methods(ssm)
- Two threads cannot execute static synchronized
methods of the same class at the same time. Only
ssm will be blocked. - If static data is shared between threads then
access to it must be protected by static
synchronized methods. - Synchronized Statements
- The synchronized statement enables to execute
synchronized code that acquires the lock of any
object, not just the current object, or for
durations less than the entire invocation of a
method.
- / make all elements in the array non-negative
/ - pubic static void abs(int values)
- synchronized (values)
- for (int i0 i lt values.length i)
- if (valuesi lt 0)
- valuesi -valuesi
-
-
-
The array is not changed during execution by any
other code that is similarly synchronized on the
values array
An object whose lock is to be acquired
synchronized (expr) statements
To execute when the lock is obtained.
13synchronized Statements
- Advantages of the synchronized statement
- Can define a synchronized region of code that is
smaller than a method. - Allow to synchronize on objects other than this,
allowing a number of different synchronization
designs to be implemented. A finer granularity of
locking. - Use for an inner object to synchronize on its
enclosing object
- class SeparateGroups
- private double aVal 0.0
- private double bVal 1.1
- protected final Object lockA new Object()
- protected final Object lockB new Object()
- public double getA()
- synchronized(lockA) return aVal
-
- public void setA(double val)
- synchronized (lockA) aVal val
-
- public double getB()
- synchronized(lockB) return bVal
-
- public void setB(double val)
- synchronized (lockB) bVal val
-
- public void reset()
- synchronized (lockA)
You can define separate objects to be used as
locks for each such group using synchronized
statements
14synchronized Statements
- public class Outer
- private int data
- //
- private class Inner
- void setOuterData()
- synchronized (Outer.this)
- data 12
-
-
-
-
- Use for an inner object to synchronize on its
enclosing object - An inner object is independently
synchronized-acquiring the lock of an inner
object has no effect on its enclosing objects
lock, nor does acquiring the lock of an enclosing
object affect any enclosed inner objects - Therefore, an inner class that needs to
synchronize with its enclosing object must do so
explicitly
15Wait, notifyAll, and notify
- The wait() method
- The wait() method allows a thread that is
executing a synchronized method or statement
block on that object to release the lock and wait
for a notification from another thread. - The notify() method
- The notify() method allows a thread that is
executing a synchronized method or statement
block to notify another thread that is waiting
for a lock on this object.
- Standard Pattern of Wait
- synchronized void doWhenCondition()
- while(!condition) wait()
- Do what must be done when the condition is
true -
- Notification
- synchronized void changeCondition()
- change some value used in a condition test.
- notifyAll() // or notify()
16Wait, notifyAll, and notify
- Class PrintQueue
- private SinglLinkQueueltPrintJobgt queue new
SingleLinkQueueltPrintJobgt() - public synchronized void add(PrintJob j)
- queue.add(j)
- notifyAll() // Tell waiters print job
added -
- public synchronized PrintJob remove() throws
InterruptedException - while (queue.size() 0)
- wait() // Wait for a print job
- return queue.remove()
-
17Producer Consumer Example
int element arrayr if (r gt
SIZE) r 0 --count
notifyAll() return element class
ProducerConsumers public static void
main(String args) Queue queue new
Queue() new Producer(queue).start() new
Consumer("ConsumerA", queue).start() new
Consumer("ConsumerB", queue).start() new
Consumer("ConsumerC", queue).start()
class Producer extends Thread Queue queue
Producer(Queue queue) this.queue queue
public void run() int i 0
while(true) queue.add(i)
class Consumer extends Thread String
str Queue queue Consumer(String str, Queue
queue) this.str str this.queue
queue public void run() while(true)
System.out.println(str " "
queue.remove())
class Queue private final static int SIZE
10 int array new intSIZE int r
0 int w 0 int count 0 synchronized
void add(int i) while(count SIZE)
try wait()
catch(InterruptedException ie)
ie.printStackTrace() System.exit(0)
arrayw i if (w gt SIZE)
w 0 count notifyAll()
synchronized int remove() while(count 0)
try wait()
catch(InterruptedException ie)
ie.printStackTrace() System.exit(0)
18Thread Scheduling
- class Babble extends Thread
- static boolean doYield
- static int howOften
- private String word
- Babble(String whatToSay)
- word whatToSay
-
- public void run()
- for(int i0 ilthowOften i)
- System.out.println(word)
- if (doYield)
- Thread.yield() // let other threads run
-
-
- public static void main(String args)
- doYield new Boolean(args0).booleanValue()
- howOften Integer.parseInt(args1)
- // create a thread for each world
- Ending Thread Execution
- The run method returns normally
- public static void sleep(long millis)
- public static void sleep(long millis, int nanos)
- public static void yield()
Run java Babble false 2 Did DidNot Result Did
Did did not DidNot
19Ending Thread Execution
- Three ways, which can occur thread termination
- The run method returns normally.
- The run method completes abruptly.
- The application terminates.
- public double calculate()
- // calculate a value for result
-
-
- class ShowJoin
- public static void main(String args)
- CalcThread calc new CalcThread()
- calc.start()
- doSomethingsElse()
- try
- calc.join()
- System.out.println(result is
calc.getResult()) - catch(InterruptedException e)
- System.out.println(No answer
interrupted) -
-
- // definition of doSomethingElse..
-
- Waiting for a Thread to Complete
- One thread can wait for another thread to
terminate by using one of the join method
class CalcThread extends Thread private
double result public void run() result
calculate() public double getResult()
return result
Other example Refer to the JoinDemo1.java
20Garbage Collection
- Garbage Collection
- Garbage Objects that are no longer referenced.
- Garbage Collection the process of finding and
reclaiming these objects - Mark-sweep model determines a set of roots that
contains directly reachable objects? marking ?
sweeping the dead objects (no marked) away - finalize() method the method is invoked by the
garbage collector after it determines that this
object is no longer reachable and its space is to
be reclaimed. This method might clean up any
non-memory resources used by this object.
- public class ProcessFile
- private FileReader file
- public ProcessFile(String path) throws
FileNotFoundException - file new FileReader(path)
-
- //
- public synchronized void close() throws
IOException - if (file ! null)
- file.close()
- file null
-
-
- protected void finalize() throws Throwable
- try
- close()
- finally
- super.finalize()
-
-
This ensures that the superclasss cleanup will
happen.
Other example Refer to the GcTest.java
21Interacting with the Garbage Collector
- Some methods in the System class
- public void gc() Asks the VM to expend effort
toward recycling unused objects so that their
memory can be resued. - public void runFinalization() Asks the VM to
expend effort running the finalizers of objects
that it has found to be unreachable but have not
yet had their finalizers run. - public long freeMemory()
- public long totalMemory()
- public long maxMemory() Returns the maximum
amount of memory, in bytes, that the VM will ever
attempt to use.
- public static void fullGC()
- Runtime rt Runtime.getRuntime()
- long isFree rt.freeMemory()
- long wasFree
- do
- wasFree isFree
- rt.runFinalization()
- rt.gc()
- isFree rt.freeMemory()
- while (isFree gt wasFree)
Not usually need to invoke runFinalization method.
Try the TestfullGC.java in several ways
22Reachability States and Reference Objects
- Import java.lang.ref.
- Import java.io.File
- Class DataHandler
- private File lastFile
- private WeakReferenceltbytegt lastData
- byte readFile(File file)
- byte data
- // check to see if we remember the data
- if (file.equals(lastFile))
- data lastData.get()
- if(data ! null) return data
-
- // dont remember it, read it in
- data readBytesFromFile(file)
- lastFile file
- lastData new WeakReferenceltbytegt (data)
- return data
- Reference Object
- When would like an object to be garbage collected
even though you may have a specific reference to
it. - The reference object A reference to an object
that doesnt force the object to remain reachable
if that is the only reference to the object. - The referent A reference object is an object
whose sole purpose is to maintain a reference to
another object - Strengths of Reference
- Strongly reachable
- Softly reachable SoftReference may be
reclaimed at the discretion of the GC. - Weakly reachable WeakReference will be
reclaimed by the GC. - Phantom reachable PhantomReference not
reachable, but needs explicit clearing. - Unreachable
For more details, Refer to the URL,
http//java.sun.com/j2se/1.5.0/docs/api/java/lang/
ref/package-summary.html