Java review-basic5

1. How would you write a socket client/server in Java

The server

DateServer.java
package edu.lmu.cs.networking;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;

/**
 * A TCP server that runs on port 9090.  When a client connects, it
 * sends the client the current date and time, then closes the
 * connection with that client.  Arguably just about the simplest
 * server you can write.
 */
public class DateServer {

    /**
     * Runs the server.
     */
    public static void main(String[] args) throws IOException {
        ServerSocket listener = new ServerSocket(9090);
        try {
            while (true) {
                Socket socket = listener.accept();
                try {
                    PrintWriter out =
                        new PrintWriter(socket.getOutputStream(), true);
                    out.println(new Date().toString());
                } finally {
                    socket.close();
                }
            }
        }
        finally {
            listener.close();
        }
    }
}

The Client side:

package edu.lmu.cs.networking;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;

import javax.swing.JOptionPane;

/**
 * Trivial client for the date server.
 */
public class DateClient {

    /**
     * Runs the client as an application.  First it displays a dialog
     * box asking for the IP address or hostname of a host running
     * the date server, then connects to it and displays the date that
     * it serves.
     */
    public static void main(String[] args) throws IOException {
        String serverAddress = JOptionPane.showInputDialog(
            "Enter IP Address of a machine that is\n" +
            "running the date service on port 9090:");
        Socket s = new Socket(serverAddress, 9090);
        BufferedReader input =
            new BufferedReader(new InputStreamReader(s.getInputStream()));
        String answer = input.readLine();
        JOptionPane.showMessageDialog(null, answer);
        System.exit(0);
    }
}

 

2. Main Differences Betwen Java NIO and IO:

IO                     NIO
Stream oriented Buffer oriented
Blocking IO        Non blocking IO
                         Selectors

 

3. Stream Oriented vs. Buffer Oriented

The first big difference between Java NIO and IO is that IO is stream oriented, where NIO is buffer oriented. So, what does that mean?

Java IO being stream oriented means that you read one or more bytes at a time, from a stream. What you do with the read bytes is up to you. They are not cached anywhere. Furthermore, you cannot move forth and back in the data in a stream. If you need to move forth and back in the data read from a stream, you will need to cache it in a buffer first.

Java NIO's buffer oriented approach is slightly different. Data is read into a buffer from which it is later processed. You can move forth and back in the buffer as you need to. This gives you a bit more flexibility during processing. However, you also need to check if the buffer contains all the data you need in order to fully process it. And, you need to make sure that when reading more data into the buffer, you do not overwrite data in the buffer you have not yet processed.

个人理解,这是I/O和NIO最主要的区别:

1)IO是stream-oriented 主要在于读入无法缓存,不能向前或者向前或者向后访问

2)NIO是buffer-oriented读入缓存在buffer中,可以向前或者向后进行访问

 

4. Blocking vs. Non-blocking IO

Java IO's various streams are blocking. That means, that when a thread invokes a read() or write(), that thread is blocked until there is some data to read, or the data is fully written. The thread can do nothing else in the meantime.

Java NIO's non-blocking mode enables a thread to request reading data from a channel, and only get what is currently available, or nothing at all, if no data is currently available. Rather than remain blocked until data becomes available for reading, the thread can go on with something else.

The same is true for non-blocking writing. A thread can request that some data be written to a channel, but not wait for it to be fully written. The thread can then go on and do something else in the mean time. What threads spend their idle time on when not blocked in IO calls, is usually performing IO on other channels in the meantime. That is, a single thread can now manage multiple channels of input and output.

个人理解,这也是IO与NIO的区别

1)Blocking 当stream在读写一个资源的时候其他事不能访问,直到读写操作完成

2)利用Chanel对资源的可用部分进行读写,并不影响资源的其他部分,其他部分可以继续其他的读写操作。

 

5. socket multiplexing:

Multiplexing is running multiple connections over one socket, all messages for those connections will be received on that socket (or send). So it's not two-way communication, but multiple different communication channels that are handled by one socket.

 

6. Sleep vs wait

Sleep:1 It is a static method syntax: Thread.sleep(). It makes the current thread into not running state for specified time in milli seconds.

     2 During sleep, the thread never release lock.

Wait:1 It is an Object level method. It makes the current thread into not running state.

        2 During wait, the thread can be waken by notify() or notifyAll() method in synchronized context.

 

7. Process vs thread
Thread: A thread is a single sequential flow of control within a program.

Process: A process has self-contained execution environment. A process generally has a complete,private set of basic run-time resources.

There are two types of multitasking: process-based and thread-based.

Difference: Both processes and threads are independent sequences of execution.

1 Threads runs in a shared memory space while processes run in a separate memory spaces.

2 A process can contain more than one thread. So a process is considered as "heavyweight" while a thread is deemed as "lightweight".

3 Process are heavily dependent on system resources while threads require minimal amounts of resource.

4 Modifying a main thread may affect subsequent threads while changes on a parent process will not necessarily affect child processes.

5 Threads within a process coomunicate directly while the process do not communicate so easily.

6 Threads are easy to create while processes are not that straightforward.

 

8. Life cycle of a Thread (Thread States)

A thread can be in one of the five states. According to sun, there is only 4 states in thread life cycle in java new, runnable, non-runnable and terminated. There is no running state.
But for better understanding the threads, we are explaining it in the 5 states.
The life cycle of the thread in java is controlled by JVM. The java thread states are as follows:
1.New
2.Runnable
3.Running
4.Non-Runnable (Blocked)
5.Terminated

 

posted @ 2016-09-14 03:00  whaochen  阅读(192)  评论(0编辑  收藏  举报