#Concurrency
###Benefits of Concurrency
- Exploit multicore processors
- Hide latency from slow I/O
- Keep GUI more responsive
###Processes vs Threads
- memory space
- share variables
- synchronization
#Java Concurrency ###Java Threads Each java thread has its own stack
Java threads share objects in the heap
###Race Conditions
Definition: A race condition occurs when the same memory location may be accessed by different threads simultaneously, and at least one access is a write.
###Achieving Thread Safety
- Imutability
- Don't share mutable objects across thread
- Synchronization
#Synchronization
Synchronized declaration is not inherited by subclasses
###Reentrant Lock
A thread can acquire the same lock multiple times never blocks it self
#Atomic Operations
Java basic types r/w from/to memory is atomic(except long and double)
####Java Thread Caches ####Volatile keyword ####java.util.concurrent.atomic
#Concurrency Utilities
#Locks in Java ###Implicit Locks in Java Java object has intrinsic monitor
Synchronized statement (auto release, reentrant) ###Implicit Locks in Java ReentrantLock() , try finally
###Concurrent Reading
- read-write locks
- copy-on-write
- Read require no synchronyzation
- write create a new immutable object, reassigning reference(require synchronisation)
###Guarding
- Wait, notify
- Condition, await, signal
###Deadlocks
- A program will be free of deadlocks if all threads acquire the locks in a fixed global order
- Deadlock may be caused by coarse-grained locking
- Pooled and timed lock attempts
::
if (System.identityHashCode(obj1) < System.identityHashCode(obj2)) {
synchronized(obj1) {
synchronized(obj2) {
…
}
}
}
#Thread Control ###Thread States:
- NEW
- RUNNABLE
- BLOCKED
- WAITING
- TIMED_WAITING
- TERMINATED
###Inter-thread control and synchronisation
- getPriority, setPriority, join, interrupt
- yield, sleep
- wait, notify, notifyAll
java thread
- Thread.sleep
- Thread.yield()
Similar to Thread.sleep(0), except not throwing InterruptedException
Current thread may just start up again - object.wait()
Current thread must hold the target object's lock when called Release the lock and place thread on wait queue for the lock - object.notify()/notifyAll()
Only use notify() when you are sure that any thread that might be waiting can make use of the condition causing the notification - thread.interrupt() If thread is currently blocked(wait, sleep, join), interrupt status is cleared, InterruptedException is thrown and thread is resumed
- Thread.interrupted()
Test whether the current thread has been interrupted.
The interrupted status of the thread is cleared by this method - Thread.isInterrupted() Test whether the current thread has been interrupted. The interrupted status of the thread is unaffected
- thread.join() Force the current thread to wait until another thread terminates Join responds to an interrupt on the thread by exiting, clearing interrupt status and throwing an InterruptedException
Termination Threads
- Normal termination: run() terminates
- Abnormal termination: Exception that propagates beyond run()
- System termination: Runtime.exit()
#Tasks and Task Control ###The Executor Framework Decouple task submission from task execution
Threads Pools
Runnable vs Callable:
- Runnable cannot return a value or throw checked exceptions
- Callable can return a value and throw an exception
Callable and Future
- Future represents the lifecycle of a task, which provide methods to test whether the task has completed or been cancelled, retrieve its result and cancel the task
#Fork-Join Framework
divide and conquer
Fork-Join Framework provides:
- ForkjoinTask
- need to subclass, define compute method for divide and conquer steps
- ForkJoinPool implementation of ExecutorService
#Reducing Lock Granularity
##Open Calls
Calling a method with no locks held is called an open call
#Use of polling and timeouts
##Atomic acquisition of multiple locks
Three way to avoid deadlock
- Lock ordering
- Open calls
- Acquire multiple locks in an atomic action
- If fails, then any acquired locks must be released
- Try again possibly after a delay
- Can use polling or timeout to acquire locks
Semaphores are useful for implementing resource pools
Refer to example code...
Scala is an OO language but directly supports programming with functions.
Methods can be referenced as (function) objects
Python and Ruby provide support for closures.
In comparison:
- Scala is statically type, more in the spirit of Java, with better syntax for writing in a function style.
Object definitions:
- class
- objects instances via new
- principal constructor declared in class header
- object(singleton pattern)
- case class
- no need for new
- pattern matching constructs used in case statements
Anonymous Functions
use :
var x: Type
orval x : Type
- var declares variables
- val declares constants or "patterns"
method declarations
- def eval (exp: Expr): Vaule
(exp : Expr) => eval (exp) : Expr => Value
eval (_) : Expr => Value
functions can be curried
(X,Y)=>Z
curried version is:X=>(Y=>Z)
Class delarations
- classes may have object parameters (can also be generic, have type parameters)
All class derive from a single superclass, if not explicit, then it is scala.AnyRef
Method overrides must be declared explicitly as overrides
Case classes allow pattern matching on their structural form
New instances do not need new
type Environment = (String => Int)
traits
are also called mixins
similar to Interfaces
- but may include method definitions
- role is to allow code reuse
- traits do not define data fields
abstract class Bool {
def && (x: => Bool): Bool
def || (x: => Bool): Bool
}
object False extends Bool {
def && (x: => Bool): Bool = this
def && (x: => Bool): Bool = x
}
the =>
argument says pass the argument without evaluations
Any expression or block {} of code has a value, possibly of type Unit(void in Java)
We can bind pass-by-name parameters to expressions or blocks
??
- everything is an object
- two kinds of classes
- value classes (like primitive types in java)
- reference classes
Class may have constructor arguments,
Traits and objects may not.
Constructor arguments define fields ??
Each class has a primary constructor
A class may have auxiliary constructors
Each auxiliary constructors must invoke apreceding constructor as the first statement in its definition
Construcor are not inherited
- Return type declaration is optional(Except ofr abstract or recursive methods)
- Argument types must be declared
- Definition body:
= e
: Type is determined by type ofe
={...}
: Type is determined by last expression of block{...}
Type is Unit (void in java)
- Defs without bodies are abstract
Val declares a constant value associated with a class instance
Vals may be:
- Abstract:
val limit
- Defined:
val limit = 1024
- Lazy:
lazy val limit = ackerman(5)
Var declares a variable associated to a class instance
Declaring var var x: T
is equivalent to:
def x:T
def x_=(y:T):Unit = ..some update ..
- Preconditions
- Postconditions
Subcontracting with DbC
Subclasses inherit contracts
Option[A] split into None and Some[A]
List[A] split into non-empty list cases Nil and non-empty list head :: tail
use of symbolic name (::) as a class name
1 :: 2 :: 3 :: 4 :: Nil == List(1,2,3,4)
- Classes extend most one superclass
- Interfaces may extend many interfaces
- Classes may implement many interfaces
- Interfaces may only contain method declarations In java there is only one inheritance slot
Scala also uses single inheritance of classes and "multiple inheritance" of traits
But Scala allows the same forms of definition in both classes and traits
- this allows code to be inherited via multiple sources
Traits are used
- to declare interfaces
- to define small reusable code components (also called mixins)
class C extends D with T1 with T2 with ... with Tn
- Mixins are stacked
- Mixins to the right take effect last
- protected(current and descendant classes)
- qualified(give more control over access by naming a visibility scope)
- private
apply
X => Y
(X1, X2) => Y
f (x1, x2)
f.apply(x1, x2)
Productn
_1
_2
Tuplen
Tuple2[Int, Double]
(Int, Double)
arrays as functions
Array[A]
extends Function1[Int, A]
val x : Array[A]
x(i)
x(i) = rhs
x.update (i, rhs)
Can define pattern matching independently of case classes
x=> x match { case P1 => E1 ... case Pn => En}
Extractor Object Example
object Twice {
def apply(x: Int) = x * 2
def unapply(z: Int) =
if (z%2 == 0) Some(z/2) else None
}
object TwiceTest {
val x = Twice(21)
x match {
case Twice(n) => println(n)
} // prints 21
}