在线程之间共享对象vs为每个线程创建对象

时间:2016-11-25 08:01:29

标签: java multithreading sockets

我需要将客户端 - 服务器应用程序作为我的大学决赛项目提交。

我已经弄清楚我将如何编写服务器但我对这种情况感到困惑。

因此,据说服务器仅支持一个已定义的协议(由Protocol接口表示),并且仅为使用该规则说话的客户端提供服务。为了测试服务器的功能,我编写了一个支持HTTP协议的实现,以便我可以从浏览器快速测试服务器,但有一件事让我感到困惑。

我已将服务器定义为:

public interface Server {

    // Methods...

    public void start() throws Exception;

    public Protocol getProtocol();

}

服务器的基本实现执行此操作:

public class StandardServer implements Server {

    /* Implementations */

    public synchronized final void start() throws Exception {
        try {
            while (true) {
                Socket socket = serverSocket.accept();
                // Use the protocol to handle the request
                getProtocol().handshake(socket);
            }
        } catch (IOException ex) {
            logger.error(ex);
        }
    }
}

我很困惑,这是真的需要这样做,因为我确信有更好的方法来做到这一点。

到目前为止我所考虑的是:

  • 同步getProtocol()方法。
  • 实现Protocol一个线程,然后用它来处理请求。
  • 当客户端连接并将协议对象传递给该线程时产生一个线程。

考虑到服务器每秒会获得相当数量的请求,这样做的好方法是什么?

任何源代码帮助/参考都将受到高度赞赏。

P.S:

  • 实施HTTP服务器。
  • Server
  • 会有多种实现方式

0 个答案:

没有答案
相关问题