Java REVIEW-BASIC5

Source: Internet
Author: User

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

The Serverdateserver.java Packageedu.lmu.cs.networking;Importjava.io.IOException;ImportJava.io.PrintWriter;ImportJava.net.ServerSocket;ImportJava.net.Socket;Importjava.util.Date;/*** A TCP server that is 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 can write. */ Public classDateserver {/*** Runs the server. */     Public Static voidMain (string[] args)throwsIOException {ServerSocket listener=NewServerSocket (9090); Try {             while(true) {Socket Socket=listener.accept (); Try{PrintWriter out=NewPrintWriter (Socket.getoutputstream (),true); Out.println (NewDate (). toString ()); } finally{socket.close (); }            }        }        finally{listener.close (); }    }}

The Client side:

 Packageedu.lmu.cs.networking;ImportJava.io.BufferedReader;Importjava.io.IOException;ImportJava.io.InputStreamReader;ImportJava.net.Socket;ImportJavax.swing.JOptionPane;/*** Trivial Client for the date server.*/ Public classdateclient {/*** 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 and then C     Onnects to it and displays the date that * it serves. */     Public Static voidMain (string[] args)throwsIOException {String serveraddress=Joptionpane.showinputdialog ("Enter IP address of a machine this is\n" + "running the date service on port 9090:"); Socket s=NewSocket (ServerAddress, 9090); BufferedReader input=NewBufferedReader (NewInputStreamReader (S.getinputstream ())); String Answer=Input.readline (); Joptionpane.showmessagedialog (NULL, answer); System.exit (0); }}

2. Main Differences betwen Java NIO and IO:

IO NIO
Stream Orientedbuffer oriented
Blocking io Non Blocking io
Selectors

3. Stream oriented vs. Buffer oriented

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

Java IO being stream oriented means that you read one or more bytes at a time, from a stream. What does with the read bytes are up to you. They is 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'll need to cache it in a buffer first.

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

Personal understanding, this is the main difference between I/O and NiO:

1) IO is stream-oriented mainly because read-in cannot be cached and cannot be accessed forward or forward or backward

2) NiO is buffer-oriented read into cache in buffer, can be accessed forward or backward

4. Blocking vs. Non-blocking IO

Java IO ' s various streams is blocking. That means, which when a thread invokes a read () or write (), which thread is blocked until there are some data to read, or th E 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 avail Able, or nothing at all, and if no data is currently available. Rather than remain blocked until data becomes available for reading, the thread can go in with something else.

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

Personal understanding, which is also the difference between IO and NIO

1) Blocking when the stream reads and writes a resource, other things cannot be accessed until the read-write operation is completed

2) Use Chanel to read and write the available portions of a resource without affecting other parts of the resource, and other parts can continue other read and write operations.

5. Socket multiplexing:

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

6. Sleep vs Wait

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

2 During sleep, the thread never release lock.

Wait:1 It is a Object level method. It makes the current thread to 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 is 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 and processes run in a separate memory spaces.

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

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

4 Modifying a main thread may affect subsequent threads when changes on a parent process would not necessarily affect chil D processes.

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

6 Threads is easy-to-create while processes is not that straightforward.

8. Life cycle of a thread (thread states)

A thread can is in one of the five states. According to Sun, there are 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 is explaining it in the 5 states.
The life cycle of the "thread in Java" is a controlled by JVM. The Java thread states is as follows:
1.New
2.Runnable
3.Running
4.non-runnable (Blocked)
5.Terminated

Java REVIEW-BASIC5

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.