CSCI 201 Final

¡Supera tus tareas y exámenes ahora con Quizwiz!

Internet Protocol (IP)

- An IP address uniquely identifies the computer on the internet - Consists of four dotted decimal numbers between 0 and 255 - They are often mapped to meaningful names called domain names - Special servers called Domain Name Servers (DNS) translate host names into IP addresses - A low-level protocol for delivering data from one computer to another across the internet in packets

IP addresses

- Broken into a network address and a host address - IPv4 are: 32 bit integer, broken into 4 numbers of 8 bits each - IPv6: 128 bits, separated into 8 sets of 4 hexadecimals (if all 4 of those are 0, then it's omitted)

CORBA Request

- CORBA clients communicate with an IDL stub, generated by the IDL file - CORBA servers communicate with an IDL skeleton, also generated by the IDL file - The Object Request Broker (ORB) in the middle performs the communication and passes the data along in a standardized way

Producer/Consumer Problem

- Famous problem for concurrent programming - Could be a deadlock

Thread pool advantages

- If you start a bunch of threads, there might be performance issues, like limiting throughput - Thread pools help manage the number of threads executing concurrently - If a thread's done, it can be used rather than creating a new one - If a thread terminates due to failing, another thread will be created to replace it The execute() method will execute the thread at some point in the future They also give more info on the state of the threads: ExecutorService.isTerminated() -> checks if all threads are done ExecutorService.shutdown() -> shutdown after all threads have terminated ExecutorService.shutdownNow() -> shutdown NOW

CORBA

- OS and language-independent - Uses IDL to map programming languages to OMG standards - Lets computer applications work together over networks

RNC Runtime Lifecycle

1) Client code calls a procedure in the Client Stub, like a local procedure 2) The client stub packs the parameters into a message - what's called "marshalling" 3) The client stub sends the message to the server 4) The server stub receives the message 5) The server stub unpacks the parameters from the message - what's called "unmarshalling" 6) The server stub calls the server procedure just like a local procedure

IDL Process

1) To create a distributed application, first define the IDL, defining the objects that will be able to be transmitted between client and server when a method is called - the methods, return types, and parameters are also defined in the IDL 2) IDLs define a list of variable types - Strings, integers, etc. module someApp interface someThing { int sum(int a, int b); }; }; modules are like packages, interfaces are like interfaces or abstract classes in C++

IPv4 Classes (WRITE DOWN)

<------ 32 bits ------>, range of host addresses Class A: 0 | Network | Host | 1.0.0.0 - 127.255.255.255, first 8 bits allocated to network Class B: 10 | Network | Host | 128.0.0.0 - 191.255.255, first 16 bits allocated to network Class C: 110 | Network | Host | 192.0.0.0 - 223.255.255.255, first 24 bits allocated to network Class D: 1110 | Multicast Address | 224.0.0.0 - 239.255.255.255, no bits allotted to host Class E: 11110 | Reserved for Future Use | 240.0.0.0 - 255.255.255.255, no bits allotted to host

Comparison/Boolean operators

= equal to <> or != not equal to < less than <= > >= not (negation) and (conjunction) or (disjunction) * -> stands for all the attributes, like: select * from Student where deptID = 'CS' -> this will get you all the attributes of every student in the CS department

Flushing

A buffer exists into which data is written before it's sent along the socket - that buffer won't transmit the data until it fills up UNLESS we flush

Calling start() vs run()

Calling run() will just execute that code, it won't do it simultaneously.

Process Scheduling in CPU

Can't determine when a process will go into CPU, only signal that it's ready - The algorithm by which processes gets switched in is specific to the OS

Web Services

Client and server applications that communicate over HTTP to implement RPCs, language and platform-independent, data is transmitted in a standardized XML format

Client App

Client needs both the IP address of the server and the port it's running the app on

Cooperation among Threads

Conditions are used to facilitate communication among threads. await() - causes the current thread to wait until the condition is signaled, signal() - wakes up one waiting thread signalAll() - wakes all waiting threads You create a condition from a Lock object. The await() method causes the thread to wait and releases the lock on the condition; but once the condition is right, the thread reacquires the lock and continues executing. You must first acquire the lock before invoking methods on a Condition.

Database System

Consists of a database, the software that stores and manages data in the database, and the application programs that present data and enable the user to interact with the database system.

Relation database systems

Database systems based on the relational data model, which has three key components: 1) Structure - Defines the representation of the data 2) Integrity - Imposes constraints on the data 3) Language - Provides the means for accessing and manipulating data

DHCP

Dynamic Host Control Protocol - These are used for a computer or router to automatically assign IP addresses and other network configuration (like the gateway and subnet mask) to computers on the network - They can be private or public IP addresses - Most routers assign private IP addresses - Routers commonly have DHCP servers built into them

Sockets

Endpoints of logical connections between two hosts and can be used to send and receive data

DNS Resource Records

Every domain has a set of resource records associated with it, which is what the DNS will return -> the resource records associated with the domain A resource record consists of 5 items: 1) Domain name - name of the record 2) Time to live - higher the value, more stable the record 3) Class - always IN for internet resources 4) Type - what kind of record (like SOA - start of authority, A - IP address of host, MX - mail exchange, value is a priority, domain willing to accept email) 5) Value - value associated with this record

yield()

Moves thread from running state to ready, and the OS decides which thread to put in now - could be the same thread if no other threads are waiting

Multithreaded vs. Parallel vs. Distributed Programming

Multithreaded - multiple sections of a process, or multiple processes that appear to execute simultaneously Parallel - multiple processes or multiple sections of a process executing simultaneously in different cores of a CPU, or on different CPUs Distributed - multiple processes or multiple parts of a process executing simultaneously on different computers

NAT

Network Address Translation (or, IP masquerading) allows a computer to have a private IP address. - Since private IPs can't be accessed by hosts outside local network, a NAT server (usually implemented in a router) substitutes its own public IP address for the private one - A NAT server must have a NAT table that links the private IP address and TCP/UDP source port combination to the destination IP address: since the NAT server's IP address replaces the private IP in the packet, the destination computer's response will go to the NAT server, and it must know the port so it knows which computer to forward the response

How to get network/subnet address from IP and subnet mask

Perform a logical AND operation: 137.229.154.221 = 1000 1001 1110 0101 1001 .... 255.255.224.0 = 1111 1111 1111 1111 1110 ... 137.229.128.0 = 1000 1001 1110 0101 1000 ... This subnet address provides So the subnet mask provided 19 bits (19 1's) for the network address, and 13 bits for the host address The subnet mask can never contain fewer bits than the number of bits in the network address

Programs vs. Processes vs. Threads

Programs - an executable in memory, typically on secondary storage Processes - an executing instance of a program, sometimes called a task Thread - any section of code inside a process that appears to be executing simultaneously; shares the resources allocated to the process by the OS kernel

Public and Private IP addresses

Public IPs can be seen by any computer in the world and are required to communicate on the internet Private IPs are usually behind a firewall, so explicit access isn't possible, they must use NAT to communicate on the Internet (maps them to an IP), they're in the following ranges: Class A - 10.0.0.0 - 10.255.255.255 (2^0 = 1 network, with 2^24 addresses) Class B - 172.16.0.0 - 172.31.255.255 (2^4 = 16 networks with 2^16 addresses) Class C - 192.168.0.0 - 192.168.255.255 (2^8 = 256 networks with 2^8 hosts on each network)

join()

Puts thread in waiting state, specifies it wants this thread to wait for another thread to complete before it continues

RMI Dynamic Code Loading

RMI can download the definition of a class if it's not defined in the JVM - All the types and behaviors of an object's class can be transmitted to a remote JVM - New types and behaviors can be introduced into a remote JVM, dynamically extending the capabilties/behavior of an application

RMI overview

RMI is a Java implementation of RPC, referred to as a distributed object application - An RMI server creates some remote objects, makes references to those objects accessible, and waits for clients to invoke methods on these objects - An RMI client obtains references to these remote objects on the server and invokes methods on them (RMI clients can locate these references through an RMI registry, as long as the remote objects have been registered with the RMI server) - The guts of remote communication between server and client are handled by the RMI, and remote communication looks like regular Java method invocations to the programmer - The client can pass a class to a remote server and have it execute methods on that class

RPC Synchronization

RPCs can be either blocking or non-blocking - A blocking RPC will stop execution until it receives a response from the server - A non-blocking RPC will continue executing while it waits for a response (typically done through multithreading or parallel programming)

JAX-RS

Representational State Transfer (REST) is an architectural style of client-server applications centered around the transfer of resources through requests and responses using Uniform Resource Identifiers (URI) - Communication is over HTTP, without requirement of SOAP, XML, or WSDL - a REST resource might be XML, HTML, plain text, PDF, JPEG, or other type - this resource can be retrieved, updated, or deleted based on permissions - REST uses HTTP, which is stateless, but state can be maintained with cookies, URI rewriting, and hidden form fields

Server Socket

To establish a server, you must create a server socket and attach it to a port - where the server listens for connections. The port identifies the TCP service on the socket - port numbers range from 0 to 65536, but numbers 0-1024 are reserved ServerSocket s = new ServerSocket(port); Socket se = s.accept(); YOU should run the socket.accept() method in its own thread (separate from the GUI, if applicable), as it can take time to execute.

Data transmission through sockets

To get an input or output stream: getInputStream(), getOutputStream on a Socket object or, wrap it like so: PrintWriter pw = new PrintWriter(socket.getOutputStream());

The Synchronized keyword

To prevent race conditions, we have to stop more than one thread from accessing a certain part of the program simultaneously, called the critical region / critical section. You can use the keyword "synchronized" in the method declaration so only one thread can access it at a time. A synchronized method gets a lock before it executes, which allows it to exclude other threads. For an instance method, the lock is on the object for which the method was invoked; for a static method, the lock is on the class. If one thread invokes a synchronized instance method on an object, the lock of that object is acquired first, then the method is executed, and finally the lock is released; another thread invoking the same method is blocked until the lock is released. The same is true if it's a static method, but with the lock on the class instead.

Simple Queries

To retrieve information from tables, use a SELECT statement: select column-list (i.e. firstName, mi, lastName) from table-list (i.e. Course) *optional* [where condition;] (i.e. deptId = 'CS')

Port

Used because, since more than one networked program can run on a computer at a time, we need a way to identify them: A port is typically in the range of 0 - 65535 (16 bits) - Ports 0 - 1023 are reserved for well-known applications, so root or administrator access is necessary to run a program on a port in that range - Ports 1024 - 49151 are registered ports, can be used by any application - Ports 49152 - 65335 are dynamic or private ports, typically used by the OS when an application needs to pass an application off to a non-registered port

Joining Tables

Used for getting info from multiple tables select lastName, firstName, courseID from Student, Enrollment where Student.ssn = Enrollment.ssn and lastName = 'Smith';

IPv6 Header

Version - which version of IP is being used (constant value 0110) ▪ Traffic Class - differentiated services (6 bits) and explicit congestion notification (2 bits) › Quality of service › End-to-end notification of network congestion without dropping packets ▪ Flow Label - tells routers that packets with same label should stay on the same path ▪ Payload Length - size of payload in octets ▪ Next Header - specifies the type of the next header ▪ Hop Limit - replaces the time to live field in IPv4 ▪ Source Address - IPv6 address of sending node ▪ Destination Address - IPv6 address of destination node

Thread Priorities

setPriority(int) Thread.MIN_PRIORITY is 1 Thread.NORM_PRIORITY is 5 Thread.MAX_PRIORITY is 10 The JVM tries to execute the highest priority thread, chosen based on a probabilistic algorithm - there is a chance lower priority threads will still execute, though

Create / Drop Tables

create table tableName ( courseID char(5), subjectId char(4) not null, courseNum integer, title varchar(50) not null, primary key (courseID) ); if a table's no longer needed: drop table tableNAME; If a table being dropped is referenced by other tables, you have to drop those tables first. To comment a line, precede it with two dashes: --

Thread States

A thread can New, Ready, Running, Blocked, or Finished New - when the thread's newly created Ready - after a thread is started by calling its start() method; it's runnable but may not be running yet if the CPU hasn't allocated time to it Running - when a thread begins executing; can become Ready if its time expires or a yield() method is called Blocked - becomes inactive, whether if the join(), sleep() or wait() method was called, or if waiting for user input; a blocked thread may be reactivated if the action blocking it is reversed Finished - after the thread has completed executing its run() method isAlive() finds the state of the thread, returns true if a thread is in the Ready, Blocked, or Running state; and returns false if a thread is New and hasn't started, or if it is Finished.

Monitor

A monitor is an object with mutual exclusion and synchronization capabilities -> all objects can be monitors. - The 'synchronized' keyword enables the use of monitors; methods or individual blocks of code can be synchronized - An object becomes a monitor once a thread locks it using the synchronized keyword - A thread can call wait() inside a monitor, releasing the lock -> that thread must be awakened in another thread with notify() or notifyAll() to move back to a ready state

Race condition, thread safe

A race condition is when different tasks are accessing a common resource in a way that causes a conflict; a class is said to be thread-safe if an object of this class doesn't cause a race condition in the presence of multiple threads.

Relation

A relation is actually a table that consists of nonduplicate rows. Record - A row of a table, also called a TUPLE Attribute - name for the column, a column represents the value of a single attribute of the record.

Database

A repository of information that form information.

Server Software

A server can't listen to a port on another server. - So, the only data the server application needs to receive messages is the port on which to listen - Multiple networked applications can all run on the same computer, as long as they're using different ports

Thread

A thread is the flow of execution, from beginning to end, of a task. It provides the mechanism for running a task; you can launch multiple threads from a program concurrently in Java. In single-processor systems, the multiple threads share CPU time - called time sharing. Every task in Java is an instance of the Runnable interface, called a runnable object. A thread is basically an object that facilitates execution of a task.

Determine host range

After you get the subnet/network address in binary, how many bits were reserved for the host, add them to that binary

Distributed Computing

Also known as Remote Procedure Calls (RPC), which is an inter-process communication mechanism that allows a program to execute a procedure in another address space: - this could be another computer, or another program running within the same computer Some RBC frameworks: - Remote Method Invocation (RMI) - Common Object Request Broker Architecture (CORBA) - Web Services - XML-RPC - JSON-RPC etc.

Interface Definition Language

An IDL provides a specification to describe a software component's interface (language-independent way to specify a shared interface so two programs can communicate) - Commonly used in RPCs when the languages between client and server might be different (the mapping between variables in each of the languages to a common format must be defined in an IDL) NO IDL for RMI cause it's all Java, but some examples: - Object Management Group (OMG) -> used by CORBA

Synchronized Collections

ArrayList, LinkedList, and Map - NOT thread-safe Vector, Stack, Hashtable - ARE thread-safe The Collections class has static methods for wrapping a collection into a synchronized version (i.e. one that is thread-safe), creating what are called synchronization wrappers. You can return a collection, a list from a specified list, and a map, set, sorted map and sorted set from the specified inputs. Invoking synchronizedCollection(Collection c) returns a new Collection object, in which all the methods that access and update the original collection c are synchronized. But to use the iterator to traverse the collection, use a synchronized(collectionName) block, otherwise you will throw a ConcurrentModificationException if the collection is modified while you iterate over it: or, get a lock on the object while you iterate, and use the same lock on that object for when you add items to it.

Time slicing

How the OS automatically switches different threads into and out of the CPU - efficient because: 1) CPU sits idle a lot of the time, waiting for input, when the user isn't doing anything Java programs already have 2 threads: main() and garbage collector

JAX-WS vs JAX-RS

JAX-WS is used in enterprise applications with advanced Quality of Service (QoS) requirements › Supports the WS-* set of protocols, providing standards for security and reliability (through SOAP) ▪ JAX-RS is used for web applications using the REST architectural pattern › Stateless operations (can withstand server restart) › Scalability › Architectural simplicity (use off the shelf components) › Resources can be accessed using a variety of formats, so it is not limited solely to SOAP

JAX-WS

Java API for XML Web Services - Uses XML messages following Simple Object Access Protocol (SOAP) - Operations offered by the service are included in the Web Services Description Language (WSDL) Server side: - the developer specifies the web service operations by defining methods in an interface - create one or more classes that implement those interfaces - create a WSDL document to let clients know what web services are exposed Client side: - Create a proxy, which is a local object representing the service - Create a program that invokes methods on the proxy JAX-WS will generate and parse the SOAP messages and convert the API class to and from SOAP

Some SQL Statements

SHOW - SHOW WHERE x -> displays parts of a table CREATE DATABASE - CREATE DATABASE databaseName USE - USE databaseName - changes database context CREATE TABLE - CREATE TABLE name (column1Name datatype, etc.); INSERT - INSERT INTO tableName(column1, col2, etc.) VALUES (value1, value2, etc.); UPDATE - UPDATE tableName SET someColumn = someValue where someColumn = originalValue; DELETE - DELETE FROM tableName WHERE someColumn = someValue SELECT - 1) what columns you want to return and 2) what tables you want them from (or use * for all columns - SELECT * FROM Student): - SELECT s.fname, s.lname, g.letterGrade FROM student s, grade g, class c WHERE s.studentID=g.studentID AND g.classID=c.classID AND c.prefix='CSCI' AND c.number=201; DROP - DROP TABLE tableName/DATABASE databaseName/ FOREIGN KEY fk1(columnName) REFERENCES otherTable(sameColumnName);

RMI Message Passing Protocol

Since RMI client and server are both written in Java, objects can be passed between them - done so using serialization

Subnet

Since network address are so scarce, sometimes we take a few bits away from the host address to make a subnet within the network - To implement subnetting, you need a subnet mask that marks the split between the network and the subnet/hosk combination: these consist of all 1's followed by all 0's: 255.255.255.0 = 11111111 11111111 11111111 00000000 BUT 255.255.255.2 = 11111111 11111111 11111111 00000010 -> NOT VALID Subnet masks can also be written in slash notation: where the number after the slash indicates the number of bits to be used in the subnet address (corresponds to the number of 1's in the subnet mask) The 0's represent the number of bits reserved for the host (if there 6 0's, there are 2^6 = 64 host addresses for that subnet)

Deadlocks

Sometimes two or more threads need to acquire locks on several shared objects, which could cause a deadlock, when each thread has the lock on one of the objects but is waiting for the other. Avoid it using a technique called resource ordering, where you assign an order to all the objects whose locks must be acquire and ensure the thread acquires the locks in that order.

Thread Pools

Starting a new thread for each task is inefficient, so we use a thread pool instead to manage tasks executing concurrently. There is the Executor interface for executing tasks in a thread pool, and the ExecutorService interface for managing and controlling tasks, and it's a subinterface of Executor. From the Executors class, use the newFixedThreadPool(int) to create a fixed number of threads in a pool, and this will return an ExecutorService object. If a thread completes a task, it can be reused to execute another task - if a thread terminates before shutdown, a new thread will be created to replace it if all other threads are idle and there are still tasks to be done. The newCachedThreadPool() creates a new thread if all the threads in the pool are not idle and there are tasks to be executed; a thread in a cached pool will be terminated if it's inactive for 60 seconds. ExecutorService executor = Executors.newFixedThreadPool(3); executor.excute(new Runnable(paramaters)); ... executor.shutdown(); // tells the executor to shut down - no new tasks can be accepted, but existing tasks will continue to finish, unlike the shutdownNow() method, which returns a list of unfinished tasks.

Parallel Computing

Studies software systems where components located on networked components communicate through message passing - Individual processes have only a partial knowledge of the problem - Message passing can be accomplished through Remote Procedure Calls (RPC) or message queues (shared memory) - The term is also used for programs with multiple pieces running within multiple processors/cores within the same computer

Convert IP address to binary

Take: 192.168.5.2 Must do: 128, 64, 32, 16, 8, 2, 1 (8 bits) 128 goes into 192 = 1 with 64 as remainder 64 goes into 64 = 1 with 0 as remainder so place 0's for the remaining 6 bits 192 == 11000000 128 goes into 168 = 1 with 40 as remainder 64 does not go into 40 = 0 but 32 does = 1 with remainder of 8 16 does not go into 8 = 0 but 8 does = 1 with remainder of 0 so place 0's for the remaining 3 bits 128 == 10101000 5 does not go 168 = 0 64 doesn't either = 0 32 doesn't = 0 16 doesn't = 0 8 doesn't = 0 4 goes into 5 = 1 with remainder of 1 2 doesn't go into 1 = 0 1 does go into 1 = 1 with remainder of 0 00000101 2 ==00000010

sleep()

Takes thread out of the CPU for specified number of milliseconds - Doesn't mean that the thread will be picked up immediately after that amount of time, it will just go back into the "ready" state from the "sleep" state - Can cause InterruptedException if interrupt() is called while it's sleeping

Creating Tasks

Tasks are objects, implementing the Runnable interface - which only contains the run() method. A task must be executed in a thread: Thread thread = new Thread(task); then tell the JVM it's ready to run like: thread.start(); When the run() method completes, the thread terminates. Invoking run() directly doesn't create a new thread, so don't do it.

Thread Class

The Thread class implements Runnable interface - which means you could write the run() method inside the Thread class, but it's not recommended because you're mixing the task and the mechanism of running the task. Thread's methods: isAlive() returns if a thread is currently running setPriority(int) can set priority from 1 to 10 join() waits for the thread it's called on to finish sleep(millis : long) puts a thread to sleep for specified number of milliseconds yield() - temporarily releases time for other threads interrupt() - interrupts the thread To call sleep(), surround the call with a try, catch(InterruptedException ex) block, putting it around the loop if sleep() is called inside a loop. Threads inherit priority of the thread that created it. For setPriority(), the Thread class has the int constants MIN_PRIORITY, NORM_PRIORITY (5, the priority of the main thread), and MAX_PRIORITY. The JVM always picks the currently runnable thread with the highest priority, and lower-priority threads can only run when no higher-priority threads are running. If all the priorities are equal, they all get an equal portion of CPU time, called round-robin scheduling.

Client Sockets

The client makes this statement to request a connection to a server: Socket s = new Socket(serverName, port); -> the client's port is automatically chosen by the JVM, the port specified in the parameter belongs to the server serverName is the server's Internet host name

Serving multiple clients

The connection to each client is handled by one thread. Create a thread for each connection: while(true) { Socket socket = serverSocket.accept(); Thread thread = new ThreadClass(socket); thread.start(); } You use the same port for the server every time. Each thread for each connection creates its own data input and output streams that receive and send data to a client.

SQL

The universal language for accessing relational database systems; it can be used on any relational database system, like MySQL.

Database management system

These are designed for professionals, application programs are built on top of these - so you can look at application programs as the INTERFACES between the database system and its users.

TCP and User Datagram Protocol

These are two higher-level protocols used in conjunction with IP: Java allows for both stream-based and packet-based data transmission Transmission Control Protocol: - enables two hosts to make a connection and exchange streams of data - guarantees deliver of data and that packets will be delivered in the same order they were sent - used for stream-based data transmission - can detect lost transmissions and resubmit them, so transmissions are lossless and reliable User Datagram Protocol: - low-overhead, connectionless, host-to-host protocol that's used over the IP - allows an application program on one computer to send a datagram to an application program on another computer - used for packet-based data transmission - can't guarantee lossless transmission

Semaphore

These can be used to restrict the number of threads that access a shared resource. A thread must acquire permission from a semaphore before accessing the resource, and after it's done with the resource, the thread must return the permit back to the semaphore. To create a semaphore, specify number of permits and, optionally, the fairness policy. Use acquire() to acquire a permit (if none is available, the thread is blocked until one is available), and release(), which releases the permit back to the semaphore - good idea to include that statement in the finally{} block so it gets executed even if there are exceptions.

PreparedStatement

These can execute precompiled SQL statements that do or do not have parameters. It is a subinterface of Statement. PreparedStatement prepStat = connection.prepareStatement("insert into tableName (column1, column2) " + "values(?,?)"); The question marks are placeholders for parameters. To set the parameters: prepStat.setX(int parameter index, X value); i.e. -> prepStat.setString(1, "Jack"); After setting the parameters, you can execute it just like a regular Statement, except they don't have parameters: prepStat.executeQuery();

Integrity Constraints

These impose a condition that all the legal values in a table must satisfy superkey: An attribute or a set of attributes that uniquely identifies the relation - that is, no two tuples have the same values on a superkey key: a key K is a minimal superkey, meaning any proper subset of K is not a superkey, and a relation can have several keys, in which case each of the keys is called a CANDIDATE key Domain constraints (INTRArelational constraint - only involves one relation) - These specify the permissible values for an attribute, like integers, fixed-length strings, variant-length strings, or a range of values, or whether it can be null Primary Key constraints (INTRArelational constraint) - one of the candidate keys designated by the database designer Foreign Key constraints (INTERrelational constraint - involves more than one relation) - the common attributes between relations, and these constraints define the relationships among relations - a set of attributes FK is a foreign key in a relation R that references relation T if: 1) the attributes in FK have the same domain as the primary key in T, and 2) a nonnull value on FK in R must match a primary key value in T

JDBC

This provides Java programmers with a uniform interface for accessing and manipulating relational databases. - You need a JDBC Driver to access the MySQL database. - Four key interfaces are involved: 1) Driver - a JDBC application loads an appropriate driver with this interface 2) Connection - connects to the database using this interface 3) Statement - creates and executes SQL statements using this interface 4) ResultSet - processes the result using this interface, if the statements return results

Why Synchronization

Thread synchronization is used to coordinate the execution of dependent threads - Sometimes we want some control over when threads execute, or what code can be accessed simultaneously - Shared resources can cause problems

IPv4 Header - WRITE DOWN

Version - which version of IP is being used (though there is a different header for IPv6) ▪ IHL (Internet Header Length) - tells how long the header is, in 32-bit words. The minimum value is 5, maximum is 15 (limiting the header to 60 bytes) ▪ Type of Service - intended to distinguish between different classes of service, such as reliability and speed, though most routers ignore this field ▪ Total Length - maximum length is 65535 bytes ▪ Identification - all fragments of a datagram contain the same Identification value ▪ DF - Don't Fragment ▪ MF - More Fragments, used to know when the last fragment of a datagram has arrived ▪ Fragment Offset - where in the current datagram this fragment belongs ▪ Time to Live (TTL) - counter used to limit packet lifetimes based on number of hops, decremented on each hop ▪ Protocol - protocol used in data portion of the IP packet, such as IPv4, tunneled, encapsulated, MANET, exterior gateway protocol, etc. ▪ Header Checksum - verifies the header only and must be recomputed at each hop since the TTL changes ▪ Options - are not used by all routers, so are irrelevant

Contention / Starvation

When a lower-priority thread never gets a chance to run because there are always higher-priority threads, or a same-priority thread that never yields. To avoid this, the thread with higher priority must periodically call the sleep() or yield() method to give threads with a lower or the same priority a chance to run.

Message Passing

When a procedure is invoked in another address space (normally on another computer), data needs to be passed to it, and message passing does this. - It's just passing data in an agreed-upon protocol - Each RPC framework has its own protocol, and they're not interchangeable, but if the protocol is generic enough you might be able to have the two applications be written in different languages and still work

Parallel Programming

With multiple processors now, software can use parallel programming to take advantage of this, using the Fork/Join framework. Fork- take a problem, divide into distinct subproblems Join - take the solution to all these subproblems and fit them all together into the one solution for the entire problem ForkJoinTask class defines a task, which is executed in an instance of ForkJoinPool. invoke() and invokeAll(tasks) on ForkJoinPool explicitly invokes fork() to execute the tasks and join() to wait until they are complete, and return a result, if any. RecursiveAction (doesn't return a value) and RecursiveTask (does return a value) are subclasses of ForkJoinTask - since ForkJoinTask is abstract, you should define a task using one or the other of these two classes. You should override the compute() method to specify how a task is performed.

Synchronization using Locks

You can also manually call locks for greater control. A lock is an instance of the Lock interface. ReentrantLock is a concrete implementation of Lock for creating mutually exclusive locks. You can include in the constructor a boolean for the "fairness policy", with true guaranteeing that the longest-waiting thread will obtain the lock first, and false granting locks arbitrarily (fair locks accessed by many threads may have worse performance, but have smaller variances in times to obtain locks and prevent starvation). lockObject.lock() acquires the lock: lock.lock(); try { code....} catch (InterruptedException ex) {} finally { lock.unlock(); } unlock() releases the lock. newCondition() can create any number of Condition objects, used for thread communication.

Sending and Receiving Objects (Server <-> Client)

You can instantiante the ObjectOutputStream and ObjectInputStream from socket streams, but the objects must be serializable -> to do so, the class for the object must implement the Serializable interface.

Synchronized blocks

You can synchronize more than just this object, but any object: synchronized (expr) { ....} The expression expr must evaluate to an object reference; if the object is already locked by another thread, the thread is blocked until the lock is released; when a lock is obtained on the object, the statements in the synchronized block are executed, and then the lock is released. So you only have to synchronize part of your code, not entire methods necessarily.

Blocking Queues

You can use ArrayBlockingQueue, LinkedBlockingQueue, and PriorityBlockingQueue for blocking queues: These cause a thread to block when you try to add an element to a full queue, or remove an element from an empty queue. Has put() and take()

Creating a database

drop database if exists NAME; create database NAME; use NAME;

Java program's steps to access a database

import java.sql.*; 1. Loading drivers -Class.forName("com.mysql.jdbc.Driver"); 2. Establishing connections Connection connection = DriverManager.getConnection(databaseURL); - where databaseURL = jdbc:mysql://hostname/dbname, username, password 3. Creating statements - If a Connection object is a cable linking your program to a database, then a Statement is a cart delivering SQL statements along that cable: Statement statement = connection.createStatement(); 4. Executing Statements statement.executeUpdate(String sql); ResultSet resultSet = statement.executeQuery(String sqlQuery); 5. Processing ResultSet - A ResultSet contains a table whose current row can be retrieved, where the initial row position is null, and you can use the next() method to move to the next row resultSet.next(); resultSet.getString(1) -> where 1 is the column number, with the column numbers beginning at 1 connection.close();

Insert, Update, and Delete

insert into tableName[(column1, column2,...,column)] values(value1, value2,...., valuen); If the column names are ommitted, all the column values for the record must be entered, even though they have defaults. update tableName set column1 = newValue1 [--if necessary--], column2 = newValue2,.... where condition; (like, title = 'some name') delete from tableName where condition; (i.e. title = 'another name') delete from tableName; -> this deletes all the records from that table

ExecutorService

newCachedThreadPool() -> for thread pool that creates new threads as needed and reuses old ones as available newFixedThreadPool(int numThreads) -> reuses a fixed number of threads newScheduledThreadPool(int corePoolSize) -> can schedule commands to run after a given delay, or run periodically newSingleThreadExecutor() -> executes one thread executorService.execute(new Thread());


Conjuntos de estudio relacionados

Chapter 22 CUTTING TOOL TECHNOLOGY

View Set

Ratio and Proportional Reasoning

View Set

Social Studies- Lesson 2: Central America and the Caribbean

View Set