16

What are the main differences between CGI and Java servlets?

ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
Jakub Mach
  • 1,109
  • 3
  • 10
  • 19

4 Answers4

28

Servlets are run in one process (HTTP server with additional features, which called Servlet Container) and they exist as long as that process exists.

CGI means every time there's client request, HTTP server creates new instance of process to serve this request. This is performance killer. Additionally, since there's new process per each request, it means CGI can't aggregate data from several requests in memory, as Servlets can, and must resort to external persistent storage (file or DB). This is performance killer as well.

Victor Sorokin
  • 11,878
  • 2
  • 35
  • 51
  • To my understanding, if I store data in session variables, that can be aggregated over multiple requests. How is it different from the way Servlets handle this? – NurShomik Jul 12 '16 at 21:12
  • 2
    @NurShomik 'data variables'' here mean variables on server, not on client. Since every request spawns new server-side process, it can not easily access server-side session variables or any other data from previous requess, unless via some persistent storage or IPC to some long-running process. This is bad for performance as well. – Victor Sorokin Jul 12 '16 at 21:16
  • Also, CGI Scripts such as PHP stores session data in files - thus uses external persistent storage. – NurShomik Jul 12 '16 at 21:45
6

Biggest difference is that CGI died a decade+ ago.

Servlets are a standard, Java CGI never really was.

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
3

Java servlets run in some kind of container (Tomcat, JBoss, Glassfish, Jetty etc) which needs to be running to serve request.

CGI normally spawns a new process for each request which (considering starting a JVM is somewhat expensive) is not the best solution for Java.

Roger Lindsjö
  • 11,330
  • 1
  • 42
  • 53
2

At a minimum, using Java servlets in a servlet container should provide better performance. Using any type of CGI with Java is most likely having to spawn new Java processes for each request, which is less than ideal. In working with Java on the server-side from the web, using Servlets is really the best approach.

ziesemer
  • 27,712
  • 8
  • 86
  • 94