Advance Java ProgrammingUnit 816 min read
CORBA, RMI, and Advanced Java Distributed Tech
Unit 8 of Advance Java Programming introduces CORBA (Common Object Request Broker Architecture), RMI (Remote Method Invocation), and other distributed computing technologies, explaining how they enable communication between objects across networks, their architectures, and real-world applications in banking, e-commerce
TAKEAWAYS:
- CORBA and RMI are distributed object computing frameworks that allow remote method calls without tight coupling between client and server.
- Marshalling/unmarshalling converts Java objects to byte streams for network transmission and back.
- CORBA uses IDL (Interface Definition Language) to define interfaces, while RMI relies on Java’s built-in serialization.
- RMI is simpler but Java-specific; CORBA is platform-independent and supports multiple languages.
- Event handling in distributed systems (e.g., CORBA’s event service) mimics GUI event models but over networks.
- Security (e.g., SSL/TLS in RMI) and transaction management are critical in real-world deployments like NEPSE stock trading or eSewa transactions.
1. Distributed Computing Basics
Distributed computing involves multiple machines working together to achieve a common goal. Key challenges:
- Transparency: Clients should not know if a method call is local or remote.
- Heterogeneity: Systems may use different languages/OS (e.g., Java on a server, Python on a client).
- Performance: Minimize latency (e.g., NTC’s CDN for faster website loading).
Real-world example:
- NEPSE (Nepal Stock Exchange): Uses distributed systems to handle real-time stock trading. When you buy/sell shares via an app, the request is routed through a CORBA/RMI-like system to match buyers/sellers across servers. The system must ensure atomic transactions (all-or-nothing) and low latency (milliseconds).
2. Remote Method Invocation (RMI)
RMI allows a Java object to invoke methods on another object across a network as if it were local.
How RMI Works
- Client calls a remote method.
- RMI runtime marshalls (serializes) arguments into a byte stream.
- Network transmits the byte stream to the server.
- Server unmarshalls the arguments, executes the method, and returns results.
- Client receives the response.
Visual: RMI Communication Flow
sequenceDiagram
participant Client as Client Machine
participant RMI_Runtime as RMI Runtime (Client)
participant Network as Network
participant Server as Server Machine
participant RMI_Runtime_S as RMI Runtime (Server)
Client->>RMI_Runtime: Call remote method (e.g., `getMax(10, 20, 30)`)
RMI_Runtime->>Network: Marshal arguments → byte stream
Network->>RMI_Runtime_S: Send byte stream
RMI_Runtime_S->>Server: Unmarshal → Java objects
Server->>Server: Execute method → returns `30`
Server->>RMI_Runtime_S: Marshal result → byte stream
RMI_Runtime_S->>Network: Send response
Network->>RMI_Runtime: Receive byte stream
RMI_Runtime->>Client: Unmarshal → return `30`Key Components
| Component | Role |
|---|---|
| Stub | Client-side proxy; forwards calls to the skeleton. |
| Skeleton | Server-side proxy; receives calls and invokes the actual object. |
| Registry | Acts like a phonebook (e.g., rmiregistry) to locate remote objects. |
| Remote Object | Object whose methods can be called remotely (extends java.rmi.Remote). |
Example: Greatest Number Finder (RMI)
Client Code
import java.rmi.*;
public class RMIClient {
public static void main(String[] args) {
try {
// Lookup remote object (like a phonebook entry)
Remote obj = Naming.lookup("rmi://localhost:1099/Calculator");
Calculator calc = (Calculator) obj;
int max = calc.getMax(10, 20, 30);
System.out.println("Greatest: " + max); // Output: 30
} catch (Exception e) {
e.printStackTrace();
}
}
}
Server Code
import java.rmi.*;
import java.rmi.server.*;
public class Calculator extends UnicastRemoteObject implements CalculatorInterface {
public Calculator() throws RemoteException {}
@Override
public int getMax(int a, int b, int c) {
return Math.max(Math.max(a, b), c);
}
public static void main(String[] args) {
try {
Calculator calc = new Calculator();
Naming.rebind("rmi://localhost:1099/Calculator", calc);
System.out.println("Server ready...");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Interface (CalculatorInterface)
import java.rmi.*;
public interface CalculatorInterface extends Remote {
int getMax(int a, int b, int c) throws RemoteException;
}
Trace Table: RMI Execution
| Step | Client Action | Server Action | Network Action |
|---|---|---|---|
| 1 | Calls Naming.lookup() |
Registry returns stub | — |
| 2 | Stub marshals (10, 20, 30) |
Skeleton unmarshals → (10, 20, 30) |
Sends byte stream |
| 3 | — | getMax() computes 30 |
Sends 30 as byte stream |
| 4 | Stub unmarshals 30 |
— | — |
Advantages of RMI:
- Simple for Java-only systems.
- Built into Java (no extra libraries needed).
- Supports firewalls via dynamic ports.
Disadvantages:
- Java-specific: Cannot mix with C++/Python objects.
- Serialization limitations: Complex objects (e.g., GUI components) may fail.
- No built-in security: Requires manual SSL/TLS setup (e.g., for eSewa transactions).
3. CORBA (Common Object Request Broker Architecture)
CORBA is a platform-independent standard for distributed objects. It decouples clients and servers using an ORB (Object Request Broker).
Key Concepts
IDL (Interface Definition Language):
- Defines interfaces independently of programming language.
- Example:
interface Calculator { long getMax(in long a, in long b, in long c); }; - Compiled into stubs/skeletons for Java/C++/Python.
ORB (Object Request Broker):
- Mediates communication between client and server.
- Handles marshalling/unmarshalling, location transparency, and object activation.
IIOP (Internet Inter-ORB Protocol):
- Standard protocol for CORBA communication (like HTTP for web).
Visual: CORBA Architecture
CORBA vs. RMI: Comparison
| Feature | CORBA | RMI |
|---|---|---|
| Language | Multi-language (Java, C++, Python) | Java-only |
| IDL | Yes (Interface Definition Language) | No (uses Java interfaces) |
| Protocol | IIOP (standard) | Java-specific RMI protocol |
| Portability | High (works across languages/OS) | Low (Java-only) |
| Complexity | High (requires ORB setup) | Low (built into Java) |
| Use Case | Enterprise systems (e.g., banking) | Java-based apps (e.g., internal tools) |
Example: CORBA Calculator (Simplified)
- Define IDL:
interface Calculator { long getMax(in long a, in long b, in long c); }; - Generate stubs/skeletons (using
idl2javatool). - Client Code (Java):
import org.omg.CORBA.*; import org.omg.CosNaming.*; public class CORBAClient { public static void main(String[] args) { try { // Initialize ORB ORB orb = ORB.init(args, null); // Get naming context org.omg.CORBA.Object objRef = orb.resolve_initial_references("NameService"); NamingContext nc = NamingContextHelper.narrow(objRef); // Lookup calculator NameComponent[] path = nc.to_name("Calculator"); org.omg.CORBA.Object calcObj = nc.resolve(path); Calculator calc = CalculatorHelper.narrow(calcObj); // Call method long max = calc.getMax(10, 20, 30); System.out.println("Greatest: " + max); // Output: 30 } catch (Exception e) { e.printStackTrace(); } } } - Server Code (Java):
import org.omg.CORBA.*; import org.omg.CosNaming.*; public class CORBAServer implements CalculatorPOA { public long getMax(long a, long b, long c) { return Math.max(Math.max(a, b), c); } public static void main(String[] args) { try { // Initialize ORB ORB orb = ORB.init(args, null); // Create calculator object Calculator calc = new CORBAServer(); // Get object reference org.omg.CORBA.Object objRef = orb.create_object( calc._this(), "Calculator"); // Register with naming service org.omg.CORBA.Object nameService = orb.resolve_initial_references("NameService"); NamingContext nc = NamingContextHelper.narrow(nameService); NameComponent[] path = nc.to_name("Calculator"); nc.rebind(path, objRef); System.out.println("Server ready..."); orb.run(); } catch (Exception e) { e.printStackTrace(); } } }
Real-world tie-in:
- Pathao’s Ride Dispatch System: Uses CORBA-like distributed architecture to match drivers with riders in real-time. When you request a ride, the app communicates with a central dispatcher server (like a CORBA object) to find the nearest driver. The system must handle high concurrency (thousands of requests/sec) and low latency (sub-second response).
4. Marshalling and Unmarshalling
Marshalling: Converting Java objects to a byte stream for network transmission. Unmarshalling: Reconstructing objects from the byte stream.
Example: Marshalling an Integer
sequenceDiagram participant Client participant Marshaller participant Network Client->>Marshaller: Marshal(int x=5) Marshaller->>Client: byte[] [0x05, 0x00, 0x00, 0x00] Client->>Network: Send byte stream Network->>Server: Receive byte stream Server->>Marshaller: Unmarshal(byte[]) Marshaller->>Server: int x=5 Server->>Server: Process x
Visual: Marshalled Data Structure
| Data Type | Marshalled Format (Example) |
|---|---|
int |
4-byte big-endian (e.g., 0x00000005) |
String |
Length (4 bytes) + UTF-8 chars |
Object |
Class name + serialized fields |
Why it matters:
- eSewa’s Transaction Processing: When you transfer money, your request (e.g., "transfer 1000 to user X") is marshalled into a byte stream, sent to eSewa’s servers, and unmarshalled to update databases. If marshalling fails, the transaction crashes (like a failed Daraz order due to network issues).
5. Other Advanced Technologies
a) Adapter Classes (Adapter Pattern)
Used to convert interfaces of existing classes to fit into another interface. Example:
- GUI Event Handling: A button’s
onClick()must match a listener’sactionPerformed(). - CORBA/RMI: Adapters bridge legacy systems (e.g., converting a C++ library to a CORBA object).
Mermaid Diagram: Adapter Pattern
b) Event Handling in Distributed Systems
- CORBA Event Service: Allows objects to publish/subscribe to events (e.g., stock price updates).
- Example: A Ncell app notifies you of a new call via an event listener (like a CORBA subscriber).
Visual: CORBA Event Service
c) Security in Distributed Systems
- RMI: Uses Java’s built-in security manager (but can be bypassed).
- CORBA: Supports SSL/TLS and authentication (e.g., for NEPSE trades).
- Example: When you log into Khalti, the payment request is secured via TLS encryption (like CORBA’s secure IIOP).
6. Exam Tips
Compare CORBA and RMI:
- Always include language support, IDL vs. Java interfaces, and protocol (IIOP vs. RMI protocol).
- Example answer:
CORBA is multi-language and uses IDL, while RMI is Java-only and relies on Java serialization. CORBA’s IIOP is standardized, whereas RMI’s protocol is Java-specific.
Marshalling/Unmarshalling:
- Explain why it’s needed (network transmission) and how it works (byte streams).
- Example trace:
When a client calls
getMax(10, 20, 30), RMI marshalls the integers into a byte array[0x0000000A, 0x00000014, 0x0000001E]and sends it to the server.
CORBA IDL:
- Know how to write IDL (e.g.,
interface Calculator { long getMax(...); }) and its role in language independence.
- Know how to write IDL (e.g.,
RMI Code:
- Always include:
Remoteinterface.UnicastRemoteObjectorRemoteException.Naming.lookup()/Naming.rebind().
- Example question: "Write RMI code for a remote calculator." → Include both client and server with
getMax().
- Always include:
Real-world links:
- Tie concepts to Nepalese apps (e.g., "CORBA’s event service is like Pathao’s driver-rider matching").
- Avoid vague answers; name specific products (eSewa, NEPSE, Ncell).
Diagrams:
- For RMI/CORBA, always draw:
- Client-server flow (sequence diagram).
- Marshalling/unmarshalling steps.
- ORB vs. RMI runtime components.
- For RMI/CORBA, always draw:
In the Real World
NEPSE Stock Trading:
- Technology: CORBA/RMI-like distributed system.
- How it uses this unit: When you buy shares, your order is marshalled into a byte stream, sent to NEPSE’s servers, and unmarshalled to update the ledger. The system must handle millions of transactions/day with sub-second latency.
eSewa’s Payment Gateway:
- Technology: RMI for internal Java services.
- How it uses this unit: When you transfer money, eSewa’s backend uses RMI to call remote banking APIs (e.g., "debit user A, credit user B"). The system serializes transaction data (e.g., amount, timestamp) for secure transfer.
Pathao’s Ride Dispatch:
- Technology: CORBA event service.
- How it uses this unit: Pathao’s app subscribes to driver location updates (like CORBA events). When you request a ride, the app publishes an event ("need a ride near Thapathali"), and the system matches you with the nearest driver in <30 seconds.
Worked Example: RMI vs. CORBA for a Loan Calculator
Scenario: A bank wants to offer a remote loan calculator accessible via Java/C++ apps.
Option 1: RMI (Java-only)
- Pros: Simple, no ORB setup.
- Cons: Cannot be used by C++/Python apps.
- Code Snippet (Server):
public class LoanCalculator extends UnicastRemoteObject implements LoanInterface { public double calculateEMI(double principal, double rate, int years) { double monthlyRate = rate / 1200; int n = years * 12; return (principal * monthlyRate * Math.pow(1 + monthlyRate, n)) / (Math.pow(1 + monthlyRate, n) - 1); } }
Option 2: CORBA (Multi-language)
- Pros: Works with C++/Python clients.
- Cons: Requires ORB setup (e.g., TAO, JacORB).
- IDL:
interface LoanCalculator { double calculateEMI(in double principal, in double rate, in int years); }; - Java Server:
public class LoanCalculatorPOA implements LoanCalculatorPOA { public double calculateEMI(double p, double r, int y) { // Same formula as RMI } }
Which to choose?
- Use RMI if the bank’s apps are all Java (e.g., internal tools).
- Use CORBA if the bank needs to integrate with third-party systems (e.g., a C++-based risk analysis tool).
Based on the TU BCA syllabus for Advance Java Programming (CACS354), unit 8.
Discussion
Loading…