ICLP c1 Java1
ICLP c1 Java1
programare
Threads and shared memory — JAVA
FMI @ UNIBUC
1
Threads and shared memory 1
1
Operating Systems Concepts, 9th edition, by A. Silberschatz, P. B. Galvin, and
G. Gagne
2
Threads and shared memory
Threads
3
Example (Service Server Arhitecture)
4
Benefits
• Responsiveness
• may allow continued execution if part of process is blocked
• especially important for user interfaces
• Resource Sharing
• Scalability
• process can take advantage of multiprocessor architectures
5
Concurrency vs parallelism
6
Single vs Multithreaded process
7
Shared Memory
Benefits
• Efficiency: all threads have direct acecss to the memory
• Simplicity: Accessing shared memory using same model as for
sequential processes
8
Synchronization – Mutex (MUTual EXclusion)
10
Thread state
11
Thread life-cycle (source: HowToDoInJava.com)
12
Thread creation
Direct
• by deriving Thread class
• by implementing the Runable interface
Abstract
• Using the Executors class
13
Thread creation using Runnable
Standard
public class HelloRunnable implements Runnable {
public void run() { System.out.println("Hello thread!"); }
public static void main(String args[]) {
Thread t = new Thread (new HelloRunnable());
t.start();
} }
14
Definirea unui thread ca subclasa a clasei Thread
15
public class Thread implements Runnable
• The exit method of class Runtime has been called and the
security manager permits the exit operation to take place.
• All threads that are not daemon threads have died, either
• by returning from the call to the run method or
• by throwing an exception that propagates beyond the run
method.
2
Daemon thread: low priority thread servicing user threads (e.g. garbage
collector thread)
17
Thread.sleep() and InterruptedException
18
sleep, handling the InterruptedException
19
currentThread, getName
20
isAlive, join with timeout, and interrupt
21
Rulare MessageLoopInterrupted
22
ThreadLocal: variables local to the thread
24
Thread interference
24
Thread synchronization mechanism
Intrinsic locks
25
Thread syncronization
Synchronized methods
private synchronized void syncMethod () {
//method body
}
Synchronized code
synchronized (object reference){
// code
}
26
When calling a synchronized method
27
Solving interference by synchronization (on statements)
28
Solving interference through synchronized methods
29
Lock properties
• Only one thread can hold a given lock at any given time
30
Warnings
31