How unit 3 is examined
This unit covers multithreading, networking (URLs, sockets, RMI) and JDBC; no question on any of them appears in the supplied papers, so each topic is a compact fallback answer that still carries the full-mark points.
Multithreading: Thread States, Priorities and Thread Scheduling, Life Cycle of a Thread, Thread Synchronization, Creating and Executing Threads, Multithreading with GUI, Monitors and Monitor Locks
<span style="display:inline-block;padding:.16em .6em;border:1.5px solid currentColor;border-radius:999px;font-size:.68em;font-weight:700;letter-spacing:.06em;text-transform:uppercase;opacity:.75">Not asked since 2022</span>
Definition. <mark>Multithreading is the concurrent execution of two or more threads inside one program, where a thread is a lightweight path of execution that shares the memory of its process.</mark>
Key points.
- A thread is created in one of two ways: by extending the
Threadclass and overridingrun(), or by implementing theRunnableinterface and passing the object to aThreadconstructor. - Calling
start()makes the JVM create a new call stack and invokerun()there, whereas callingrun()directly just executes it as an ordinary method in the current thread. - The life cycle has five states: New (object created), Runnable (after
start(), waiting for the CPU), Running (executing), Blocked/Waiting/Timed Waiting (waiting for a lock,wait(),sleep()orjoin()) and Terminated (run finished). - Every thread has a priority from 1 (
MIN_PRIORITY) to 10 (MAX_PRIORITY) with a default of 5 (NORM_PRIORITY), and the scheduler prefers higher-priority Runnable threads, but this is only a hint and not a guarantee. - Scheduling is either time-slicing, where each thread gets a fixed quantum, or preemptive, where a higher-priority thread interrupts a lower one;
yield()offers the CPU to an equal-priority thread. - Without control, two threads updating shared data cause a race condition, so shared code is marked
synchronized. - Every Java object has one monitor lock; a thread must acquire it before entering a synchronized method or block, other threads block until it is released, and
wait(),notify()andnotifyAll()let threads coordinate while holding the monitor. - In GUI programs (Swing) the event-dispatch thread draws the screen, so long tasks must run in a separate worker thread and update components through
SwingUtilities.invokeLater(), otherwise the window freezes.
Diagram. <figure class="ds-fig" style="margin:1.4rem 0;overflow-x:auto"><svg xmlns="http://www.w3.org/2000/svg" id="dsfig-u3-01" viewBox="0 0 467 209" width="467" height="209" role="img" aria-label="Thread life cycle. Run = Runnable, Rng = Running, Blk = Blocked or Waiting, End = Terminated"><style>#dsfig-u3-01 .e{stroke:#454C5A;stroke-width:1.4;fill:none}#dsfig-u3-01 .e.hi{stroke:#2340B8;stroke-width:2.6}#dsfig-u3-01 .n{fill:#FFFFFF;stroke:#16181D;stroke-width:1.4}#dsfig-u3-01 .n.hi{fill:#E3E9FC;stroke:#2340B8;stroke-width:2.2}#dsfig-u3-01 .n.rb-b{fill:#16181D;stroke:#16181D}#dsfig-u3-01 .n.rb-r{fill:#BD3227;stroke:#BD3227}#dsfig-u3-01 text{font-family:"JetBrains Mono",ui-monospace,Menlo,Consolas,monospace;font-size:13px}#dsfig-u3-01 .t{fill:#16181D;font-weight:500}#dsfig-u3-01 .t.inv{fill:#FFFFFF;font-weight:700}#dsfig-u3-01 .kd{stroke:#16181D;stroke-width:1.2}#dsfig-u3-01 .dot{fill:#16181D}#dsfig-u3-01 .ann{fill:#2340B8;font-size:11px;font-weight:700}#dsfig-u3-01 .lbl{fill:#6F7787;font-family:system-ui,-apple-system,sans-serif;font-size:12px;font-weight:700}#dsfig-u3-01 .ptr{fill:#2340B8;font-size:12px;font-weight:700}#dsfig-u3-01 .ah{fill:#454C5A}#dsfig-u3-01 .ah.hi{fill:#2340B8}#dsfig-u3-01 .wl rect{fill:#FFFFFF;stroke:#DCE0E7}#dsfig-u3-01 .wl .t{font-size:12px;font-weight:700}#dsfig-u3-01 .wl.hi rect{fill:#2340B8;stroke:#2340B8}#dsfig-u3-01 .wl.hi .t{fill:#FFFFFF}html.dark #dsfig-u3-01 .e{stroke:#B1B7C3}html.dark #dsfig-u3-01 .e.hi{stroke:#8FA3FF}html.dark #dsfig-u3-01 .n{fill:#161920;stroke:#E6E8ED}html.dark #dsfig-u3-01 .n.hi{fill:#1E2748;stroke:#8FA3FF}html.dark #dsfig-u3-01 .n.rb-b{fill:#E6E8ED;stroke:#E6E8ED}html.dark #dsfig-u3-01 .n.rb-r{fill:#FF7E71;stroke:#FF7E71}html.dark #dsfig-u3-01 .t{fill:#E6E8ED}html.dark #dsfig-u3-01 .t.inv{fill:#0F1115}html.dark #dsfig-u3-01 .kd{stroke:#E6E8ED}html.dark #dsfig-u3-01 .dot{fill:#E6E8ED}html.dark #dsfig-u3-01 .ann{fill:#8FA3FF}html.dark #dsfig-u3-01 .lbl{fill:#858D9C}html.dark #dsfig-u3-01 .ptr{fill:#8FA3FF}html.dark #dsfig-u3-01 .ah{fill:#B1B7C3}html.dark #dsfig-u3-01 .ah.hi{fill:#8FA3FF}html.dark #dsfig-u3-01 .wl rect{fill:#161920;stroke:#2A2E37}html.dark #dsfig-u3-01 .wl.hi rect{fill:#8FA3FF;stroke:#8FA3FF}html.dark #dsfig-u3-01 .wl.hi .t{fill:#0F1115}</style><defs><marker id="ah1" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path class="ah" d="M0,1 L9,5 L0,9 z"/></marker><marker id="ahh1" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path class="ah hi" d="M0,1 L9,5 L0,9 z"/></marker></defs><path class="e" d="M59,40 L148,40" marker-end="url(#ah1)"/><path class="e" d="M186,48.4 Q233.5,72 279.2,49.3" marker-end="url(#ah1)"/><path class="e" d="M281,31.6 Q233.5,8 187.8,30.7" marker-end="url(#ah1)"/><path class="e" d="M298,59 L298,148" marker-end="url(#ah1)"/><path class="e" d="M284.6,155.6 L183.8,54.8" marker-end="url(#ah1)"/><path class="e" d="M317,40 L406,40" marker-end="url(#ah1)"/><g class="wl"><rect x="81" y="31" width="47.1" height="18" rx="9"/><text class="t" x="104.5" y="40" dy=".35em" text-anchor="middle">start</text></g><g class="wl"><rect x="209.5" y="51.4" width="47.1" height="18" rx="9"/><text class="t" x="233.1" y="60.4" dy=".35em" text-anchor="middle">sched</text></g><g class="wl"><rect x="210.4" y="10.6" width="47.1" height="18" rx="9"/><text class="t" x="233.9" y="19.6" dy=".35em" text-anchor="middle">yield</text></g><g class="wl"><rect x="277.6" y="95.5" width="40.8" height="18" rx="9"/><text class="t" x="298" y="104.5" dy=".35em" text-anchor="middle">wait</text></g><g class="wl"><rect x="206.4" y="95.5" width="54.3" height="18" rx="9"/><text class="t" x="233.5" y="104.5" dy=".35em" text-anchor="middle">notify</text></g><g class="wl"><rect x="342.1" y="31" width="40.8" height="18" rx="9"/><text class="t" x="362.5" y="40" dy=".35em" text-anchor="middle">done</text></g><circle class="n" cx="40" cy="40" r="18"/><text class="t" x="40" y="40" dy=".35em" text-anchor="middle">New</text><circle class="n" cx="169" cy="40" r="18"/><text class="t" x="169" y="40" dy=".35em" text-anchor="middle">Run</text><circle class="n" cx="298" cy="40" r="18"/><text class="t" x="298" y="40" dy=".35em" text-anchor="middle">Rng</text><circle class="n" cx="298" cy="169" r="18"/><text class="t" x="298" y="169" dy=".35em" text-anchor="middle">Blk</text><circle class="n" cx="427" cy="40" r="18"/><text class="t" x="427" y="40" dy=".35em" text-anchor="middle">End</text></svg><figcaption style="font-size:.82em;opacity:.72;margin-top:.45rem">Thread life cycle. Run = Runnable, Rng = Running, Blk = Blocked or Waiting, End = Terminated</figcaption></figure>
Example.
class Counter {
private int c = 0;
synchronized void inc() { c++; } // one thread at a time
int get() { return c; }
}
// two threads each call inc() 1000 times -> get() is always 2000
Answer frame. Open with the definition and the two ways to create a thread; draw the life-cycle diagram; then develop the states, priority, scheduling, synchronization and monitor points in that order; close with one line saying synchronization trades speed for data safety.
Pitfall: Writing
t.run()instead oft.start()gives no concurrency at all.
Networking: Manipulating URLs, Reading a file on a Web Server, Socket programming, Security and the Network, RMI, Networking
<span style="display:inline-block;padding:.16em .6em;border:1.5px solid currentColor;border-radius:999px;font-size:.68em;font-weight:700;letter-spacing:.06em;text-transform:uppercase;opacity:.75">Not asked since 2022</span>
Definition. <mark>Java networking, provided by the java.net package, lets programs on different machines communicate using URLs, TCP sockets and remote method calls.</mark>
Key points.
- The
URLclass represents a web address and gives its parts throughgetProtocol(),getHost(),getPort()andgetPath(), so a program can manipulate a URL without parsing the string itself. - To read a file on a web server, create a
URL, callopenStream()(oropenConnection()for more control) and wrap the returned stream in aBufferedReaderto read it line by line. - Socket programming follows the client-server model over TCP: the server creates a
ServerSocketon a port and blocks inaccept(), and the client creates aSocket(host, port), after which both sides exchange data throughgetInputStream()andgetOutputStream(). - UDP is the connectionless alternative, using
DatagramSocketandDatagramPacket; it is faster but gives no delivery guarantee. - RMI (Remote Method Invocation) lets an object call methods of an object running in another JVM as if it were local, with a remote interface extending
Remote, a server object registered in the RMI registry, and a client-side stub that marshals the call. - Every remote method must declare
throws RemoteException, because network failures can occur on any call. - Security on the network is enforced by the security manager, which restricts what downloaded code may do (for example, applets can connect only to their origin host), and by signed code and SSL/TLS encryption.
Example.
ServerSocket ss = new ServerSocket(5000);
Socket s = ss.accept(); // waits for a client
BufferedReader in = new BufferedReader(
new InputStreamReader(s.getInputStream()));
System.out.println(in.readLine()); // prints the client's line
Answer frame. Open with the definition of java.net; draw a client and server box joined by a socket; then develop URL, reading a web file, sockets, RMI and security in that order; close with one line on when to choose sockets versus RMI.
Pitfall: Forgetting that
accept()blocks, so a single-threaded server serves only one client at a time.
Accessing Databases with JDBC: Relational Database, SQL, MySQL, Oracle
<span style="display:inline-block;padding:.16em .6em;border:1.5px solid currentColor;border-radius:999px;font-size:.68em;font-weight:700;letter-spacing:.06em;text-transform:uppercase;opacity:.75">Not asked since 2022</span>
Definition. <mark>JDBC (Java Database Connectivity) is the Java API in java.sql that lets a program connect to a relational database and run SQL statements on it.</mark>
Key points.
- A relational database stores data in tables of rows and columns linked by keys, and it is queried with SQL, using statements such as
SELECT,INSERT,UPDATEandDELETE. - MySQL and Oracle are relational database systems, and each supplies its own JDBC driver (for example
com.mysql.cj.jdbc.Driver), so the same Java code works with either after changing the driver and URL. - The connection URL has the form
jdbc:mysql://localhost:3306/dbname, andDriverManager.getConnection(url, user, password)returns aConnection. - A
Statementruns plain SQL, while aPreparedStatementprecompiles a query with?placeholders, which is faster when repeated and prevents SQL injection. executeQuery()returns aResultSet, a cursor moved withnext()and read withgetInt()orgetString(), whereasexecuteUpdate()returns the number of rows changed.- Resources must be closed at the end (or opened in try-with-resources), and
SQLExceptionmust be handled.
Steps.
Step 1: Load the driver (Class.forName) and build the JDBC URL.
Step 2: Get a Connection from DriverManager.
Step 3: Create a Statement or PreparedStatement.
Step 4: Execute the SQL query or update.
Step 5: Process the ResultSet with next().
Step 6: Close the ResultSet, statement and connection.
Example.
Connection con = DriverManager.getConnection(url, "root", "pw");
PreparedStatement ps = con.prepareStatement("SELECT name FROM student WHERE id=?");
ps.setInt(1, 7);
ResultSet rs = ps.executeQuery();
while (rs.next()) System.out.println(rs.getString("name"));
con.close();
Answer frame. Open with the definition of JDBC; list the six steps in order; show the short program above; close with one line that PreparedStatement is preferred for safety.
Pitfall: Building SQL by string concatenation invites SQL injection; use placeholders.
Last-minute revision
- A thread is created by extending
Threador implementingRunnable;start()begins it,run()does not. - Thread states: New, Runnable, Running, Blocked/Waiting, Terminated.
- Priority runs from 1 to 10 with a default of 5, and it is only a scheduling hint.
synchronizedgives one monitor lock per object and prevents race conditions.wait(),notify()andnotifyAll()work only while holding the monitor.- Swing long tasks run in worker threads; screen updates use
SwingUtilities.invokeLater(). URL.openStream()reads a remote file;ServerSocket.accept()waits for a clientSocket.- TCP sockets are reliable and connection-based; UDP uses
DatagramSocketand is unreliable. - RMI needs a remote interface extending
Remote, a registry, a stub, andthrows RemoteException. - JDBC steps: driver, connection, statement, execute, result set, close.
PreparedStatementprevents SQL injection;executeQuery()gives aResultSet,executeUpdate()a row count.
Memory hooks
- Thread life: "New, Ready, Run, Wait, Die".
- Sockets: the server accepts, the client connects.
- RMI: "Interface, Impl, Registry, Stub".
- JDBC order: "Driver, Connect, Statement, Execute, Result, Close".
Coverage checklist
- Multithreading: Thread States, Priorities and Thread Scheduling, Life Cycle of a Thread, Thread Synchronization, Creating and Executing Threads, Multithreading with GUI,Monitors and Monitor Locks: no past questions.
- Networking: Manipulating URLs, Reading a file on a Web Server, Socket programming, Security and the Network, RMI, Networking: no past questions.
- Accessing Databases with JDBC: Relational Database, SQL, MySQL, Oracle: no past questions.