java面試題整理(3)
阿新 • • 發佈:2019-01-08
1.String為什麼是不可變的?
2.Tomcat,Jetty,Apache,Jboss,Nginx的區別:
tomcat與Jetty:
lighttpd,apache,nginx的區別:
3.什麼是SQL注入,如何防止SQL注入?
4.java記憶體模型中,一個物件(兩個屬性,四個方法)例項化100次,現在記憶體中的儲存狀態,幾個物件,幾個屬性,幾個方法?
5.反射的效能?如何優化?
6.spring的AOP實現細節?
它的一些主要功能:
7.執行緒同步,併發操作怎麼控制?
8.tomcat的session機制,如果讓你實現一個server,如何實現session機制?
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* @author [email protected]
* @time 2019/1/2 16:08
*/
public class ServerTest4server {
public static void main(String[] args) throws IOException {
new Server();
}
static class Server {
static volatile LinkedList socketList = new LinkedList();
public Server() throws IOException {
ExecutorService executorService = Executors.newFixedThreadPool(5);
ServerSocket serverSocket = new ServerSocket(8080);
while (true) {
final Socket socket = serverSocket.accept();
if (socket != null) socketList.add(socket);
final Iterator iterator = socketList.iterator();
while (iterator.hasNext()) {
//引用變數保證執行緒間的通訊
final Socket currSocket = (Socket) iterator.next();
//在主執行緒中將該物件移除,它是主執行緒同步的。
socketList.remove(currSocket);
executorService.execute(new Runnable() {
public void run() {
try {
InputStream inputStream = currSocket.getInputStream();
byte[] inputByte = new byte[1024];
int length;
if ((length = inputStream.read(inputByte)) != -1) {
if (length != 1024) System.out.println(new String(inputByte, 0, length, Charset.forName("utf-8")));
else System.out.println(new String(inputByte));
}
} catch (IOException e) {
e.printStackTrace();
}
try {
OutputStream outputStream = currSocket.getOutputStream();
String s = "hi,world!";
outputStream.write(s.getBytes("utf-8"));
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
}
}
}
}
import java.io.*;
import java.net.Socket;
import java.nio.charset.Charset;
/**
* @author [email protected]
* @time 2019/1/2 16:08
*/
public class ServerTest4client {
public static void main(String[] args) throws IOException, InterruptedException {
new Client();
}
static class Client{
public Client() throws IOException, InterruptedException {
Socket socket=new Socket("127.0.0.1",8080);
while (true){
OutputStream outputStream= socket.getOutputStream();
String outputString = "helloworld";
outputStream.write(outputString.getBytes("utf-8"));
InputStream inputStream= socket.getInputStream();
byte[] inputByte = new byte[1024];
int length;
if ((length = inputStream.read(inputByte)) != -1) {
if (length != 1024) System.out.println(new String(inputByte, 0, length));
else System.out.println(new String(inputByte));
}
Thread.sleep(3000);
}
}
}
}
筆記:1.當套接字的socket流顯式關閉,該socket也會關閉(無論是輸入流,還是輸出流);
2. 當輸入流採用while迴圈讀取時,可能會發生死鎖。 尤其是服務端和客戶端同時採用該方式;
3.流的多位元組read,即多位元組讀取操作,是阻塞式。 所謂阻塞是指: 必須讀到結果,儘管這個結果有可能是-1,否則它將阻塞。