【发布时间】:2014-01-25 15:34:08
【问题描述】:
在我触发这个nohup java -cp server.jar:mysql-connector.jar com.server.test.EchoMulti & 后不到一个小时,我就得到了这个错误。错误:
Exception in thread "main" java.lang.OutOfMemoryError: unable to create new native thread
at java.lang.Thread.start0(Native Method)
at java.lang.Thread.start(Unknown Source)
at com.server.test.EchoMulti.main(EchoMulti.java:14)
我是服务器和 Java 的新手。这是我在服务器和 Java 中做的第一件事,它是一款适用于 Android 游戏的多人游戏。游戏做得很好,所以有很多人尝试玩多人游戏。我已经修复了 mySQL max_connections 但现在我遇到了问题。我还想知道是否有办法在出现导致崩溃的错误时自动重新启动进程。还有一种在重启时自动启动它的方法。
导致它的 EchoMulti 类:
package com.server.test;
import java.net.*;
import java.io.*;
public class EchoMulti {
public static void main(String[] args) throws IOException {
int portNumber = 25003;
boolean listening = true;
try (ServerSocket serverSock = new ServerSocket(portNumber)) {
while (listening) {
new EchoServer(serverSock.accept()).start();
}
} catch (IOException e) {
System.err.println("Could not listen on port " + portNumber);
System.exit(-1);
}
}
}
EchoServer 类:
package com.server.test;
import java.net.*;
import java.io.*;
import java.sql.*;
import java.lang.Thread;
public class EchoServer extends Thread {
private Socket sock = null;
public EchoServer(Socket sock) {
super("EchoServer");
this.sock = sock;
}
public void run(){
String url = "jdbc:mysql://IP:3306/DB";
String username = "USER";
String password = "PASSWORD";
Connection con = null;
Statement sta = null;
ResultSet resultSet = null;
try {
//System.out.println("Connecting database...");
con = DriverManager.getConnection(url, username, password);
//System.out.println("Database connected!");
} catch (SQLException e) {
throw new RuntimeException("Cannot connect the database!", e);
}
try (
PrintWriter out = new PrintWriter(sock.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(sock.getInputStream()));
) {
String inputLine;
while ((inputLine = in.readLine()) != null) {
if(inputLine.equalsIgnoreCase("get")){
SEND SOMETHING
} else {
String catched[] = inputLine.split("\\;");
if(catched[0].equalsIgnoreCase("sub")){
SEND SOMETHING
} else if(catched[0].equalsIgnoreCase("res")){
SEND SOMETHING
}
}
}
} catch (IOException e) {
System.out.println("Exception caught when trying to listen on port 25003 or listening for a connection");
System.out.println(e.getMessage());
} finally {
//System.out.println("Closing the connection.");
if (con != null) try { con.close(); } catch (SQLException ignore) {}
try { sock.close(); } catch (IOException ignore) {} finally {}
}
}
public void close() throws IOException {
if (sock != null) sock.close();
}
}
【问题讨论】:
-
尝试增加 Java 应用程序的内存。
-
我有一个 1GHz 的 VPS、1GB 内存和 50GB 空间。也许我应该创建一个交换文件?
-
你对 RAM 的看法是对的 :) 但我设法减少了线程数。
标签: java mysql centos threadpool multiplayer