Is Hazelcast Client thread safe? - hazelcast

I cannot find this in the docs or javadocs: do I need to create one client per thread or is a client created by:
client = HazelcastClient.newHazelcastClient(cfg);
thread safe?

The client is thread-safe. Also when you get e.g. an IMap from it, it also is thread-safe.
HazelcastInstance client = HazelcastClient.newHazelcastClient(cfg)
IMap map = client.getMap("map");
So you can share this client instance with all your threads in the JVM.

Related

Share one ServerSocket connection to client between multiple threads in Kotlin

I am making a server application in Kotlin, and the server does following things:
Bind a ServerSocket port let's say 10001.
This port accepts TCP connection from clients (Users). Thread used. Works now as intended.
It also opens and Binds a local port 10002 from localhost only.
This port allows external application in local host to connect, and communicate as manager thread.
It initiate a remote connection to another server in UDP, translates TCP data from port 10001 to UDP by restructuring the data pack and visa-versa.
This thread is being created by the thread running port 10001 connection on-demand above at #1.
Now, we have 3 connections as shown below (Manager & User connections are two different Threads):
Manager(10002) --> | Kotlin | --> Remote Server
User(10001) <-----> | Server | <-- (UDP Port)
So, I want to send some commands from Manager Thread to User Thread buy specifying certain tread identifier, and that will initiate a code block in User thread to send some JSON data to user terminal.
And one of the command from Manager thread will start a remote server connection(UDP, assume a thread too) to communicate and translate data between User Thread and the remote server connection.
So in this case, how do I manage the communication between threads especially between Manager and User thread?
I have been able to create treads to accept User side connections, and it works fine now.
val socketListener_User = ServerSocket(10001)
socketListener_User.use {
while (true) {
val socket_User = socketListener_User.accept()
thread(start = true) {
/** SOME CODE HERE **/
/** THIS PART IS FOR USER THREAD **/
}
}
}
The user can send data at any time to Server as well as Manager. So the server shall be on standby for both side, and neither of them shall block each other.
It should be similar to instant messenger server, but usually IMs store data in external database and trigger the receiver to read, isn't it?
And now I believe there must be some way to establish communications channels between treads to do above tasks which I have not figured out.
After digging some docs, I ended up using cascaded MutableMaps to store the data needed to be shared between threads
In main class file, before main(), I declared vals for the data storage maps.
val msgToPeers : MutableMap<String, <Int, <String, String>>> = HashMap()
// Format: < To_ClientID, < Sequence_Num, < From_ClientID, Message_Body >>>
Next, in threads for each serversocket connection, create two sub threads
Sender Thread
Receiver Thread
In Sender Thread, construct the datamap, and add into msgToPeers by using
msgToPeers.set() or msgToPeers["$receiverClientID"] = .......
Then in Receiver Thread, run a loop to scan the map, and pick up whatever data you need only, and output to socketwriter.
Remember to use msgToPeers["receiverClientID"].remove(sequenceID) to empty the processed message before goes to next loop.
Oh, I also added a 50ms pause per loop as I needed to make sure that the sender threads to have enough time to queue the message list before the scanner takes the message and clear it.

How can a process handle multiple requests on a web server using sockets?TCP

I know that you utilize a port to address a process and that you have to use sockets for handling multiple requests on web server, but how does it work? Is the process creating multiple socket threads for each connection? Is threading the answer?
Overview
This is a great question, and one that will take a bit to explain fully. I will step through different parts of this topic below. I personally learned multi-threading in Java, which has quite an extensive concurrency library. Although my examples will be in Java, the concepts will stand between languages.
Is threading valid?
In short, yes this is a perfect use case for multi-threading, although single-threaded is fine for simple scenarios as well. However, there does exist better designs that may yield better performance and safer code. The great thing is there are loads of examples on how to do this on the internet!
Multi-Threading
Lets investigate sample code from this article, seen below.
public class Server
{
public static void main(String[] args) throws IOException
{
// server is listening on port 5056
ServerSocket ss = new ServerSocket(5056);
// running infinite loop for getting
// client request
while (true)
{
Socket s = null;
try
{
// socket object to receive incoming client requests
s = ss.accept();
System.out.println("A new client is connected : " + s);
// obtaining input and out streams
DataInputStream dis = new DataInputStream(s.getInputStream());
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
System.out.println("Assigning new thread for this client");
// create a new thread object
Thread t = new ClientHandler(s, dis, dos);
// Invoking the start() method
t.start();
}
catch (Exception e){
s.close();
e.printStackTrace();
}
}
}
}
The Server code is actually quite basic but still does the job well. Lets step through all the logic seen here:
The Server sets up on Socket 5056
The Server begins its infinite loop
The client blocks on ss.accept() until a client request is received on part 5056
The Server does relatively minimal operations (i.e. System.out logging, set up IO streams)
A Thread is created and assigned to this request
The Thread is started
The loop repeats
The mentality here is that the server acts as a dispatcher. Requests enter the server, and the server allocates workers (Threads) to complete the operations in parallel so that the server can wait for and assist the next, incoming request.
Pros
Simple, readable code
Operations in parallel allows for increased performance with proper synchronization
Cons
The dangers of multi-threading
The creation of threads is quite cumbersome and resource intensive, thus should not be a frequent operation
No re-use of threads
Must manually limit threads
Thread Pool
Lets investigate sample code from this article, seen below.
while(! isStopped()){
Socket clientSocket = null;
try {
clientSocket = this.serverSocket.accept();
} catch (IOException e) {
if(isStopped()) {
System.out.println("Server Stopped.") ;
break;
}
throw new RuntimeException("Error accepting client connection", e);
}
this.threadPool.execute(new WorkerRunnable(clientSocket,"Thread Pooled Server"));
}
Note, I excluded the setup because it is rather similar to the Multi-Threaded example. Lets step through the logic in this example.
The server waits for a request to arrive on its alloted port
The server sends the request to a handler that is given to the ThreadPool to run
The ThreadPool receives Runnable code, allocated a worker, and begin code execution in parallel
The loop repeats
The server again acts as a dispatcher; it listens for the request, receives one, and ships it to a ThreadPool. The ThreadPool abstracts the complex resource management from the developer and executes the code optimized fully. This is very similar to the multi-thread example, but all resource management is packaged into the ThreadPool. The code is reduced further from the above example, and it is much safer for non-multi-threading professionals. Note, the WorkerRunnable is only a Runnable, not a raw Thread, whilst the ClientHandler in the Multi-Thread example was a raw Thread.
Pros
Threads are managed and re-used by the pool
Further simplify code base
Inherits all benefits from the Multi-Threaded example
Cons
There is a learning curve to fully understanding pooling and different configurations of them
Notes
In Java, there exists another implementation called RMI, that attempts to abstract away the network, thus allowing the communication of Client-Server to happen as though it is on one JVM, even if it is on many. Although this as well can use multi-threading, it is another approach to the issue instead of sockets.

Transaction management and Multithreading in Hibernate 4

I have a requirement of executing parent task which may or maynot have child task. Each parent and child task should be run in thread. If something goes wrong in parent or child execution the transaction of both parent and child task must be rollback. I am using hibernate4.
If I got it, the parent and the child task will run in differents threads.
According to me it's a very bad idea that does not worth considering.
While it may be possible using jta transaction, it's clearly not the case using hibernate transaction management delegation to underlying jdbc connection (you have one connection per session and MUST NOT share an hibernate session between threads).
Using jta you will have to handle connection retrieval and transactions yourself and can't so take advantages of connection pooling and container managed transaction (spring or java ee ones). It may be overcomplicated for about no performance improvments as sharing the database connection between two threads will just probably move the bottleneck one level below.
See how to share one transaction between multi threads
According to OP expectation here is a pseudo code for Hibernate 4 standalone session management with jdbc transaction (I personnaly advise to go with a container (Java ee or spring) and JTA container managed transaction)
In hibernate.cfg.xml
<property name="hibernate.current_session_context_class">thread</property>
SessionFactory :
Configuration configuration = new Configuration();
configuration.configure("hibernate.cfg.xml");
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
SessionFactory sessionFactory = configuration.buildSessionFactory(builder.build());
The session factory should be exposed using a singleton (any way you choose you must have only one instance for the whole app)
public void executeParentTask() {
try {
sessionFactory.getCurrentSession().beginTransaction();
sessionFactory.getCurrentSession().persist(someEntity);
myChildTask.execute();
sessionFactory.getCurrentSession().getTransaction().commit();
}
catch (RuntimeException e) {
sessionFactory .getCurrentSession().getTransaction().rollback();
throw e; // or display error message
}
}
getCurrentSession() will return the session bound to the current thread. If you manage the thread execution yourself you should create the session at the beginning of the thread execution and close it at the end.
the child task will retrieve the same session than the parent one using sessionFactory.getCurrentSession()
See https://docs.jboss.org/hibernate/orm/4.3/manual/en-US/html/ch03.html#configuration-sessionfactory
http://docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#transactions-demarcation-nonmanaged
You may find this interesting too : How to configure and get session in Hibernate 4.3.4.Final?

Persist queue: serialize/deserialize queue object in node-amqp

I'm using the node-amqp module to manage rabbitmq subscriptions. Specifically, I'm assigning an exclusive/private queue to each user/session, and providing binding methods through the REST interface. I.e. "bind my queue to this exchange/routing_key pair", and "unbind my queue to this exchange/routing_key pair".
The challenge here is to avoid keeping a reference to the queue object in memory (say, in an object with module-wide scope).
Simply retrieving the queue itself from the connection each time I need it, proved difficult, since the queue object keeps tabs on bindings internally, probably to avoid violating the following from the amqp 0.9.1 reference:
The client MUST NOT attempt to unbind a queue that does not exist. Error code: not-found
I tried to simply set the queue object as a property on a session object using connect-mongo, since it uses JSON.stringify/JSON.parse on its properties. Unfortunately, the queue object fails to "stringify" due to a circular structure.
What is the best practice for persisting a queue object from the node-amqp module? Is it possible to serialize/deserialize?
I would not try to store the queue object, instead of that use an unique name for the queue that you can store. After that whenever you want to make operations over the queue you have two options:
In the case you have a previously opened "channel" to the queue, you should be able to do:
queue = connection.queues[name].
I mean connection as a node-amqp connection against rabbitMQ.
In the case you dont have a channel opened in your connection with rabbitmq, just open the channel again:
connection.queue(name = queueName, options, function(queue) {
// for example do unbind
})
I am also using REST interface to manage rabbitMQ. My connection object maintains all the queues, channels, etc... So, only the first time I try to use a queue I call to connection.queue, and the following request just retrieve the queue through connection.queues.

http listeners inside threads

I am writing a web service which has to be able to reply to multiple http requests.
From what I understand, I will need to deal with HttpListener.
What is the best method to receive a http request(or better, multiple http requests), translate it and send the results back to the caller? How safe is to use HttpListeners on threads?
Thanks
You typically set up a main thread that accepts connections and passes the request to be handled by either a new thread or a free thread in a thread pool. I'd say you're on the right track though.
You're looking for something similar to:
while (boolProcessRequests)
{
HttpListenerContext context = null;
// this line blocks until a new request arrives
context = listener.GetContext();
Thread T = new Thread((new YourRequestProcessorClass(context)).ExecuteRequest);
T.Start();
}
Edit Detailed Description If you don't have access to a web-server and need to roll your own web-service, you would use the following structure:
One main thread that accepts connections/requests and as soon as they arrive, it passes the connection to a free threat to process. Sort of like the Hostess at a restaurant that passes you to a Waiter/Waitress who will process your request.
In this case, the Hostess (main thread) has a loop:
- Wait at the door for new arrivals
- Find a free table and seat the patrons there and call the waiter to process the request.
- Go back to the door and wait.
In the code above, the requests are packaged inside the HttpListernContext object. Once they arrive, the main thread creates a new thread and a new RequestProcessor class that is initialized with the request data (context). The RequsetProcessor then uses the Response object inside the context object to respond to the request. Obviously you need to create the YourRequestProcessorClass and function like ExecuteRequest to be run by the thread.
I'm not sure what platform you're on, but you can see a .Net example for threading here and for httplistener here.

Resources