MultiThreading alternative in Java

I have a question that bothers me. For example, I have a multithreaded server, when it receives a request, it passes this request to the handler, this handler will process this request. One of the reasons why we do multithreading the server: if it is not multithreaded, when the server processes this request during a time value, another request, then this request will be deleted, since the server is now unavailable.

So, I wonder if there is an alternative to a multithreaded server, for example, can we create a queue for a server without multithreading? when he can receive another request from the queue after its completion.

+6
source share
3 answers

You still have a single-threaded mechanism with a multi-threaded server.

Consider the following skeleton - if you have an Engine that works, it can be fully single-threaded, simply passing requests in the order in which they are received. This allows you to use unsafe components in the business logic, and you managed to separate your network layer from the business logic level! This is a win-win scenario.

class Engine implements Runnable { private final Object requestLock = new Object(); private List<Request> requests = new LinkedList<Request>(); private boolean running = true; private Request nextRequest() { synchronized(requestLock) { return requests.poll(); } } /** * The engine is single threaded. It doesn't care about server connections */ public void run() { while(running) { Request request = nextRequest(); // handle your request as normal // also consider making a mechanism to send Responses } } } 
+1
source

Yes, you can have an event based server . This feature is provided by the java.nio package, although you can use a framework like netty , rather than doing it from scratch.

However, note that while this was considered a way to improve performance, it seems that a regular multi-threaded server actually offers the best performance with today's hardware and operating systems.

+2
source

Yes, you can. Have you considered methods like SEDA (i.e. event-driven methods)? You might want to explore the Netty library. This does most of the work for you when it comes to using NIO.

+2
source

Source: https://habr.com/ru/post/886508/


All Articles