Title: Distributed Programming in Java
1Distributed Programming in Java
2Patterns Interlude
- What are patterns?
- A pattern describes a design problem and a
general solution for it in a context - Captures important practices and existing, proven
methods and practices - Make design trade-offs (forces) explicit
- Patterns solve complex problems they are not
templates to be mindlessly copied
3Pattern Format
- We will use (as appropriate) three versions of
the PLoP pattern format - Long form (name, context, problem, forces,
solution, consequences, related patterns) - The elements of the long form will be described
in the next slides ... - Pattlet (name, problem, and short solution)
- Short form (short solution, structure)
4Long Pattern Form
- Name a short phrase that concisely summarizes
the pattern - Context a description of the situation when the
pattern can be applied may include a list of
patterns that were already applied (precondition) - Problem a precise statement of the problem to
be solved (how to ...)
5Long Pattern Form
- Forces the design trade-offs affected by the
pattern (push and pull the solution) - Solution description of the solution that
resolves these forces and its structure - Consequences forces resolved by the solution,
and (new) unresolved ones - Related patterns what further patterns are
needed, and for what purpose
6Where Do I Find Patterns?
- Patterns books
- Design Patterns GoF
- Patterns of Software Architecture POSA
- Enterprise Architecture Patterns EAP
- Enterprise Integration Patterns EIP
- Remoting Patterns RP
- Concurrent Programming in Java CPJ
- Patterns conferences
- PLoP, EuroPLoP, ... (www.hillside.net)
7Template Method GoF
- Create an abstract class that automates the
control sequence of ground actions - Subclasses only override hook() methods
8Use in Thread
- The Thread class uses Template Method
- start() is the template method, and
- run() the hook method
- When subclassing the Thread class ...
9Use in Thread
- However, typically you would not subclass Thread,
but implement Runnable - This results in a variation of the pattern (but
still using the same principle)
10Command GoF
- Define a class whose entire purpose is to invoke
some method on some object - Most applications restrict themselves to just one
or a small set of Command interfaces
11Use in Runnable
- Runnable is a Command interface
- To run a method in a thread you create a class
that implements Runnable
12A Particle Applet
- GUI-based program
- Displays randomly moving particles on the screen
- Uses several auxiliary classes to do most of the
work - Particle
- ParticleCanvas
- ParticleApplet
- Illustrates Template Method and Command
13(No Transcript)
14ParticleApplet
- Message sequences during applet execution
15Particle
class Particle protected int x
protected int y protected final Random rng
new Random() public Particle(int initialX,
int initialY) x initialX y
initialY public synchronized void
move() x rng.nextInt(10) 5
y rng.nextInt(20) 10 public
void draw(Graphcs g) int lx, ly
synchronized(this) lx x ly y
g.drawRect(lx, ly, 10, 10)
16ParticleCanvas
class ParticleCanvas extends Canvas private
particle particles new particle0
protected synchronized void setParticles(particle
ps) if (ps null) throw
new IllegalArgumentException(Cannot set null)
particles ps public void
paint(Graphics g) Particle ps
getParticles() for (int i0 i lt
ps.length i) psi.draw(g)
17ParticleApplet
public class ParticleApplet protected Thread
makeThread(final Particle p) // utility
Runnable runloop new Runnable() public
void run() try for()
p.move() canvas.repaint()
Thread.sleep(100) // 100msec is
arbitrary catch
(InterruptedException e) return
return new Thread(runloop)
18ParticleApplet
class ParticleApplet protected Thread threads
null // null when not running public
synchronized void start() int n 10 //
just for demo if (threads null) //
bypass if already started Particle
particles new Particlen for (int i
0 i lt n i) particlesi new
Particle(50, 50) canvas.setParticles(partic
les) threads new Threadn for
(int i 0 i lt n i) threadsi
makeThread(particlesi)
threadsi.start()
19Thread Lifecycle
- Instances of Thread progress through various
states as shown below
20Exclusion
- Preventing multiple threads from concurrently
modifying or acting upon object representations - Strategies
- Eliminate need for exclusion
- Dynamically ensure that only one thread at a time
can access object state - Structurally ensure that only one thread can ever
use an object
21Immutable Object
- If an object cannot change state, it cannot
encounter inconsistencies a multiple threads try
to change its state in incompatible ways - Programs are simpler to understand when object
are never changed ... - ... but such programs are also constrained in
what they can do (eg interaction)
22Value Object EAP
- One approach to implement Immutable Objects is
Value Object EAP - A value object is a simple object whose equality
is not based on identity - In Java Color, Integer, and String are value
objects they are also immutable - Example Money
- Operations on the Money class (eg add)create new
instances of Money
23Flyweight GoF
- Share objects for space efficiency by making them
immutable (eg font objects) - the characters stored in a word processor. Each
character represents an object that has a font
face, font size, and other formatting data. the
Flyweight pattern. - A factory maintains a pool of flyweights
- Each of the character objects contain a reference
to a flyweight which contains the required
properties. - A Flyweight design guarantees immutability
24(No Transcript)
25Synchronization
- Locking protects objects against
- low-level storage conflicts, and
- corresponding high-level invariant failures
- Without locking the desired invariant may fail
when multiple threads execute methods that write
(at least one) and read variables - Need to serialize access of such methods
26Example
class Location private double x_, y_
Location(double x, double y) x_ x y_ y
double x() return x_ double
y() return y_ void moveBy(double
dx, double dy) x_ dx y_ dy
27Possible Scenario
28Locking
- Acquire the lock on an object on entry to a
method, release it on return - Can be used to guarantee method atomicity
- Introduces potential liveness failures
29Scenario Revisited
30Locks in Java
- Every Java Object has a lock
- Manipulated through synchronized keyword
- Method or block qualifier
- Java locks are reentrant
- A thread passes synchronized, if it is free, or
it itself already holds it, otherwise waits
31Example (Resolved)
class Location private double x_, y_
Location(double x, double y) x_ x y_ y
synchronized double x() return x_
double y() synchronized (this)
return y_ synchronized void
moveBy(double dx, double dy) x_ dx
y_ dy