Object Oriented Programming 2 Flashcards
Rich API support
Doing / learning networking, parallelism, graphics, GUI, algorithms
Why is java platform independent
It runs in a virtual machine: JVM
Why learn Java?
Active development, many jobs, platform indep, tools (networking, …)
Java and Distributed Systems
Socket communication, thread management, object serialization, remote method invocations, servlets, applets
Java compilation
Programm compiled into bytecode, which the JVM executes at runtime
Object
Combines methods (behaviour) and data (state),
hide complexity, modularization, modelling of domain
How are objects defined
throught the keyword “class”
“volatile”
ensures visiblity accross threads, safe to use across threads
Interface
Defines a group of methods, classes implement them to provide functionailty, implementation enforced at compilation
static nested classes
no access to outer members, to hide access
Named constants
entirely in uppercase with underscore
Creation of Arrays:
anArray = new int[10];
float[] anArrayOfFloats;
int[] anArray = {
100, 200, 300,
400, 500, 600,
};
Casting
Cast allows access to specific object
methods
Defensive copies
gainst outside failures, ill-behaved clients, or attacks
also for getters
varargs
represent zero or
more arguments of a specified type
Parallelism (concurrency)
one computer that does multitasking, real (processors) or pseudo (threads)
Distributed system
Networked components, coordinated by messages
Server threads
within server process; handle concurrent user requests
Server processes
handle different types of access
(e.g., web, mail, file, …)
Remote Invocation
Client invocation and server result
RPC (remote procedure call) or RMI (remote method invocation)
Requires defined messaging protocoL
Server State:
Stateful (client tables)
Soft state (for given time)
Session state (for session)
Stateless
Thread-based Connection Abstraction
incoming request -> accepted by dispatcher thread
Threaded Server Design Patterns
Fix or dynamic number of threads
Re-usage of threads: thread pool (created at start), non active threads kept in pool
Thread per Request
dispatcher reveives request, for each a thread is created or assigned from pool
Worker thread: Read request
Process request
Answer request
End
Thread per Connection
Dispatcher Thread assigns client to thread
Worker thread
Read request
Process request
Answer request
Wait for next assignment or return to pool
(if client closes connection)
Thread per Service-Object
Each service-object provides
An own thread
An own queue
Dispatcher assigns request to service object queue
Service object thread reads from queue and processes -> queue serialization
Java Threads
JVM runs as a process on the operating system
JVM runs several threads (garbage collector, …)
Java.lang.Thread objects are placed into own threads
“run()” must be overridden
DON’T use Thread.sleep() for synchronization
Exact time when thread will be resumed is difficult to predict:
sequence and duration of thread execution varies, and may vary for different runs
Interface Runnable
Alternative to using run on objects derived from Thread
Synchronization
shared data, execution order ofter hard to predict
without controls, we cannot predict thread switch
Synchronization methods are needed
data consistency (data correctness)
maintain parallelism
synchronized keyword
locks an object, if a thread encounters it and it is locked, thread is put to sleep
try to synchronize specific variables
End of Java Thread
join(): blocks until a thread ends
yield(): increase probability to switch to another thread
Inside synchronized
wait() → blocks a calling Object until it gets notified that it can resume
notify() → unblocks waiting caller
notifyAll() → unblocks all waiting callers
JavaFX
Stage: window
Scene: container to fill a stage
Observers in JavaFX
implements the interface EventHandler<ActionEvent></ActionEvent>
Properties in JavaFX
Classes which implement the observer model
They can be observed
contains: values, methods to register observers, methods to update and read the observed value
Informs all registered observers
JavaFX Bindings
Mechanisms to couple properties -> Change of one property changes another property (uni or bidirectional)
JavaFX Collections
You can register observers to collections
They are notified on changes to the collection
Interfaces ObservableList, ObservableMap, ObservableSet
JavaFX Elements
“Node” is the basic element
Pane derives from Node and is basis for all container classes
Container Classes derived from Pane
- VBox: Vertical layout
- HBox: Horizontal layout
- FlowPane: Line by line layout
- BorderPane: top/bottom/left/right/center
- StackPane: on top layout
- TilePane: uniform grid layout
- GridPane: variable grid layout
- AnchorPane: anchor to border
JavaFX Interaction Elements
Control class derived from Node
Labels, Buttons, Lists, Pickers, Slider, Text Input
JavaFX Other functions
Automatization: Stylesheet support, UI definitions from FXML files
Multi-windows UIs
Web and media support
JavaFX MVP
Model
Application logic (data and methods)
Independent of GUI
View
GUI component creation and manipulation
Different views may represent parts of the model
Presenter
Flow control
Triggered by UI interaction and using/manipulating model
JavaFX Problems in Event Processing
Certain action on an Event may take long time. No other events are processed during this time, so no
window update happens.
Solution: Aim for short duration in event handling, use Threading for event handling
Submit the update to the event queue of the JavaFX Application thread using Platform.runLater()
Interface Worker
Observe state
Possibility to cancel
Class Task
Implement a single long running task
* message (ReadOnlyStringProperty)
* title (ReadOnlyStringProperty)
* value (ReadonlyObjectProperty<V>)
* workDone (ReadOnlyDoubleProperty)
* State (ReadonlyObjectProperty<Worker.State>)</Worker.State></V>
class Service
Implement repeating tasks
Class ScheduledService
Schedule of repeating tasks, coordination via properties
8 Golden Rules GUI/Application Design (Ben Shneiderman)
- Strive for consistency.
- Enable frequent users to use shortcuts.
- Offer informative feedback.
- Design dialog to yield closure.
- Offer simple error handling.
- Permit easy reversal of actions.
- Support internal locus of control.
- Reduce short-term memory load.
Wired Network types:
- PAN: Personal Area Network (USB)
- LAN: Local Area Network (Ethernet)
- MAN: Metropolitan Area Network (DSL)
- WAN: Wide Area Network (IP Routing)
Wireless Network types:
- WPAN (Bluetooth)
- WLAN (Wifi (IEEE 802.11))
- WMAN (WiMAX (IEEE 802.16))
- WWAN (GSM; UMTS; LTE, 5G)
Circuit Switching:
“plain old” telephone system
Packet Switching
compute shortest path, longer messages partitioned into packets
Virtual Circuit (Frame Relay):
determine routing path during setup
Broadcasting (e. g. WLAN):
No switching, all messages delivered to all nodes, receivers must make sense
of messages, collision detection mechanisms are needed.
Routing
Distributed Algorithm
Routers work cooperatively
Aim to compute the shortest paths
Required routing protocol
Congestion Control
Avoid overload
Trade-off latency vs. throughput
Internetwork
Integration of heterogeneous sub-nets
Unified protocol (e.g., Internet Protocol IP)
ISO-OSI 7 Layer Model
All People Seem To Need Data Protection
* Application
* Presentation
* Session
* Transport
* Network
* Datalink
* Physical
NOT used in practise
Internet Protocol IP
Virtual Network, Allows routing through multiple networks
TCP/IP (Transmission Control Protocol/Internet Protocol)
Only contains 4 of the 7 OSI Layers.
DataLink and Physical layer are combined to Host-to-Network layer (LAN)
Network layer → IP
Transport layer → TCP (or UDP)
Application layer → FTP, DNS, SMTP
Ports
for distinguishing two connections on a host.
TCP/UDP Protocol
TCP is connection-oriented, handles order, loss, duplicate packets, Bi-directional, has to be connected to IP
UDP is connectionless, only for short messages, unidirectional, IP given in message
UDP/TCP Realization in Java
Packages java.net java.io
InetAddress
– represents an Internet host by IP address and name
DatagramPacket and DatagramSocket
– used to communicate with UDP
– send one packet at a time
Socket und ServerSocket
– to establish TCP connection
– send data using InputStream and OutputStream
Broadcasting
Target are all nodes in the network
Multicasting
Receiver can select if it is a member of the group or not
multicast IP address range
Sender does not know who are the receivers
java.io
InputStream, OutputStream
Byte-oriented streams
Reader, Writer
Character-oriented streams
Semaphores
used to limit the access to critical sections of code (data), not only among threads, it is also used among
different processes by OS
Counter to limit number of parallel accesses
Reader/Writer Problem
Write access must be exclusive while read access can be shared
Prioritize writers if updates are frequent
Prioritize readers if high read throughput and rare updates
synchronization in Java
synchronized; wait/notify
semaphore implementations
custom data structures
Transactions
Abstraction of set of operations (e.g., of a client) into atomic unit
All-or-nothing execution
No interference from other concurrent transactions or server/client crashes (other process cancels transaction)
ACID Properties for Transactions
Atomicity
Transaction executed all or nothing
Consistency
Transactions transform objects from one consistent state to another
Isolation
Transactions performed without interference of other transactions
Durability
Result of successful transaction is permanently stored
Serial Equivalence for Transactions
Serial execution (with immediate, permanent write) gives correct state
two conflicting operations have to operate on same objects in the same order
locking, optimistic control, timestamp ordering, nested transactions
Locking
is pessimistic
Exclusive locks
Read/write locks (read shared, write exlcusive)
Two-phase locking
deadlock
If two transactions wait for each other to release a lock it can end in a deadlock, as both are waiting and
can’t proceed.
Deadlock prevention
Acquire all locks at beginning of transaction
lock need may not be known in advance at beginning
Deadlock detection
Maintain wait-for-graph
Test for cycles on each operation, or periodically
Optimistic Concurrency Control
Assume conflicts are sparse
Working phase, validation phase, update phase
Stream Terminal Processing
Traverse (forEach)
Search (allMatch, anyMatch)
Reduce (count, sum, average)
Collect (toArray)
Indirect Communication
Temporal/spacial decoupling (async, hide identity)
communication middleware
Persistent communication
distributed systems: frequent changes, nodes (dis)connect frequently, nodes unknown
Transient Communication
Transient async: A sends and continues, message can only be sent if B runs
Transient receiver oriented: A continues only upon message reveival is acknowledgedment (issued immediately)
Persistent Communication
Persistent asynchronous
store on sender side
Persistent synchronous
store on receiver side
Push Notifications
Distributed systems often need updates on local object changes (events)
Useful to connect heterogeneous systems
Efficient notification via multicast
IP multicast
eliver IP packets to multiple destinations
Minimize number of packets sent
Packets do not delay each other
Implementations for Group Communication
- Integrity of message content
- Guarantee of delivery to each client
- Receiving order
- Interface to add/remove clients, update list
- Monitoring of recipient status, remove inactive recipients
JGroups
Reliable group communication in Java
Has a Protocol Stack with underlying communication protocols
Channels with basic functionality for joining, leaving, sending, receiving (send via reliable multicast)
Message Queues
Reliable point-to-point communication
persistent storage of messages
Decoupling of space and time
Sender sends messages to waiting queue destined for a recipient
FIFO or priority
Publish-Subscribe
sends (publishes) structured events to an event service (broker)
Clients subscribe topics, get notified when event available
Event characterized by type and attributes
One-to-many communication
Publishers und subscribers typically do not know each other (space uncoupling)
Publish-Subscribe Type of delivery
Direct: Point to point, Multicast
Indirect: Message Queue, Server
Publish-Subscribe Subscription Models
- By Channel
- By Topic
- By Content
- By Type
Distributed Shared Memory
Parallel computing architectures → Multiprocessor shared memory
Compute-intensive operations on data partitions
Avoids explicit messaging
Needs memory protection: Use locks and semaphores
Tuplespaces
Distributed Shared Memory = Distributed Random Access Memory
Tuple Space = Distributed Associative Memory (content-adressable memory)
Asynchronous publish-subscibe system
Tuple = Message with ordered and typed attributes
Tuplespace = temporary database of tuples
Data producers that publish and subs that consume based on a pattern (<String, Int, “hello”>)
Explicit messaging
No communication transparency
Explicit marshalling
Explicit send/receive of messages
Explicit exception handling
RPC / RMI
Middleware connects caller and remote procedure
No explicit marshalling required
No explicit send/receive required
Exception handling
JAVA RMI
Middleware service which allows access to remote JAVA objects (other PC on network, localhost)
Client-server communication without need to use sockets
Modular development
Load balancing
Stubs and Skeletons
Stub code provides object access to the client who
uses a remote object (“Remote control” to remote object
)
Skeleton code manages object requests by the
object server
RMI Registry Usage
Server side: bind / rebind / unbind (name, e.g. “Counter”)
Client: lookup
Registry runs objects in own threads
Can create multiple stubs for parallel access to server objects
Pass as Value / as Reference
by value: safe from outside manipulation, store a copy
by reference: callbacks to passed object (side effects), provided by stub
RMI Design patterns
indirect communication mechanisms (tuple spaces, queues, …)
distributed MVP applications (with RMI interface)
Object Migration with RMI
process of moving objects between RMI servers
Pass object using call-by-value
copy placed on the server
copy is exported
Applications: load balancing, object validation, persistent storage
Clients may use derived classes > server needs to reload, client needs to publish via codebase server
Web-based Application Programming
integration of code with the existing client/server infrastructure
Document-oriented (sync: html, forms or async: dom)
or webservice-oriented
How to Process HTTP Interaction Requests on the
Server Side?
Java servlets
Java Servlets
Handling client requests
Derive a Servlet class from HttpServlet
Overwrite the methods doGet and/or doPost
Create HTML code or Java Server Faces in servlet and deliver
Execution of Servlets
Typically, web servers serve requests multithreaded, d, but create only one object for each Servlet
Requires synchronization of Servlet access
Servlets can share information via Servlet context
run long-lasting Servlet jobs asynchronously (startAsync, AsyncContext)
Identification of Servlet clients
getRemoteAddr() (not reliable, due to use of proxies and NAT)
getSession() creates session ID (cookie) to identify returning client
Java Server Faces (JSF)
Use external HTML code templates defined in XHTML
Embed input/output fields in the XHTML page using Expression Language (EL) statements
Fields linked to objects
AJAX
Asynchronous JavaScript and XML
Embed JavaScript (JS) code in webpages, run by browser
code sends the data to the Servlet
receives a reply and updates an element of the webpage
Programmatic updates to webpages via DOM
Webservices
provide services based on HTTP protocol which may exchange data
SOAP (Simple Object Access Protocol)
REST (representational state transfer)
e.g. JSON (JavaScript Object Notation)