How to synchronize a variable in main function to new thread? - java

I have a list of the socket in the main function, add a new socket when a new client connects to the server.
public static void main(String[] args) throws Exception {
// TODO code application logic here
server = new ServerSocket(port);
List<MySocket> sockets = new ArrayList<>();
//this is thread responsible to synchronizing
new SyncThread().start();
while(true){
Socket socket = server.accept();
MySocket mySocket = new MySocket(socket);
sockets.add(mySocket);
SocketThread.setSockets(sockets);
new SocketThread(mySocket).start();
}
}
Besides that, I also want to create a new thread that will synchronize the list of this socket to the client (by sending the list to clients periodically).
public class SyncThread extends Thread{
private static List<MySocket> sockets;
#Override
public void run(){
//send list sockets to client
}
}
How to I synchronize the list of the socket between the main function and SyncThread?

Make your list a synchronized list:
List<MySocket> sockets = Collections.synchronizedList(new ArrayList<>());
And then pass this as a constructor parameter to SyncThread:
new SyncThread(sockets).start(); // Need to add constructor parameter to class.
public class SyncThread extends Thread{
private final List<MySocket> sockets; // NOT static.
public SyncThread(List<MySocket> sockets) {
this.sockets = sockets;
}
...
}
Bear in mind that this doesn't make sockets synchronized for compound operations, e.g. iteration. For that, you'd need to explicitly synchronize on sockets; or choose a different type of list such as CopyOnWriteArrayList, which is inherently thread-safe (the choice depends on the read/write characteristics of how you use the list).
Additionally, it's rarely appropriate to extend Thread directly. Instead, pass it a Runnable:
new Thread(() -> { /* send list sockets to client */ }).start();

Related

How do I call a method in a specific socket thread using "implements Runnable"?

I have a working Java Server (Although a tad rough around the edges) which contains 3 main classes.
The first class runs the server and gets the socket to listen on a port and passes new connections to a client handler.
The second class is a threaded client handler
The third is a protocol class which is called from the client handler and processes information. Once the information is processed, the protocol class returns a processed or formatted response back to the client handler to pass to the client.
The advantage is that the second class just needs to be loaded with what is acceptable data to accept from the socket. The data can be passed to the protocol handler, and the protocol handler can be loaded with whatever protocol you want the server to use to talk to the client.
In this instance I have loaded in a telnet-based chat class.
If, for example, someone leave the chat the client handler class may execute code such as:
for (i = 0; i < currentClientsConnected; i++) {
if(threads[i] != null && threads[i] != this) {
outputLine = threads[i].serverprotocol.processInput("** " + username + " has left the room **");
threads[i].out.printf(outputLine);
}
}
This passes "** [username] has left the room **" to the serverprotocol class, which then returns the data in the best best way to transmit the message to the clients. In this case the serverprotocol class formats the message with telnet control code which tells the client to re-draw the screen, add the new message and scroll up the existing current messages in the buffer.
I may also only want the client handler class to send message to sockets where the users are in certain chat rooms for example, so I will not want to always send to all the sockets.
In my code, this is Class 1 - the server class which accepts sockets with:
while (true) {
int i;
// Try and accept the connection
try {
clientSocket = serverSocket.accept();
// System.out.printf("Remote IP:");
// System.out.printf(clientSocket.getRemoteSocketAddress().toString());
// Find an unused socket if one is available
for (i = 0; i < maxClientsAllowed; i++) {
// If found create thread
if (threads[i] == null) {
(threads[i] = new clientThread(clientSocket, threads)).start();
break;
}
}
// If all sockets are taken
if (i == maxClientsAllowed) {
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
out.printf("Server too busy. Try later.\n");
out.close();
clientSocket.close();
}
} catch(IOException e) {
System.out.println(e);}
}
and Class 2 is a class which extends thread:
class clientThread extends Thread {
private String clientName = null;
private DataInputStream in;
private PrintWriter out;
private Socket clientSocket = null;
private final clientThread[] threads;
private int currentClientsConnected;
private serverprotocol serverprotocol;
public clientThread(Socket clientSocket, clientThread[] threads) {
this.clientSocket = clientSocket;
this.threads = threads;
currentClientsConnected = threads.length;
}
public void run() {
//stuff
}
}
I have been trying desperately to see if I can get this working using implements Runnable instead, but I have had no luck in calling a thread's processInput (or maybe that should read dataToBeProcessed) method based on the instance number of the thread (Simply called i in the code here).
The closest I have seen in:
https://github.com/ico77/chat-server-client/blob/master/src/main/java/hr/ivica/chat/server/ChatServer.java
which can take advantage as running the server as a threaded pool server.
However the sendToAll function in this case writes directly to the PrintWriters associated to the socket via a HashMap. The server does not let you send to individual protocol handler classes, or even to the individual ChatServerWorker class instances. This means I can't, for example, send a message to socket 1 and 3 only and then a separate message to socket 2.
I can't find a single example online where an instance of a socket handler can be called without using extends Thread.
Specifically,I want to keep the ability to use lines like:
threads[i].out.printf(outputLine);
or
if(threads[i].[class].[var] == 'something') {
// stuff
}
Where an integer can be used to reference the thread instance, or any class vars or methods used by that thread.
Am I missing something?
Your big problem is that you are using the Threads themselves directly as the communication layer between the Server and the Client threads, something you should not do.
Instead, create your own interface Message objects that communicate the different information between the threads, and use LinkedBlockingQueue to process them.
You should probably have:
One queue for the server to receive messages
Depending on your implementation, one queue for each of the client threads to receive messages from the server, or one queue that's shared (if it's designed so that any thread can handle any message).
So you might do something like:
Message:
public interface Message {
accept(Server server);
}
Disconnection Message (I'm just going to do one):
public class DisconnectionMessage implements Message {
String username;
public void accept(Server server) {
server.handleMessage(this);
}
}
Server Runnable:
public void run() {
while(isServerOnline()) {
Message clientMessage = queue.poll();
clientMessage.accept(this);
}
}
public void handleMessage(DisconnectionMessage msg) {
// code
}
public void handleMessage(ConnectionMessage msg) {
// code
}
etc.
Client Runnable:
private final Socket socket;
private final BlockingQueue<Message> queue;
public Client(BlockingQueue<Message> queue, Socket socket) {
this.queue = queue;
this.socket = socket;
}
public void run() {
while(true) {
Message msg = receiveMessage();
queue.offer(msg);
}
}
I am not sure if I understood your question.
The short answer: if you want to make clientThread a Runnable, just do it and then change the line
(threads[i] = new clientThread(clientSocket, threads)).start();
into
(threads[i] = new Thread(new clientThread(clientSocket, threads))).start();
If you look at the documentation:
http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#Thread(java.lang.Runnable)
Threads accept objects with Runnable supertype.
The long answer: you should not store threads directly but make an abstraction that represents a Client on the server side. This abstraction should encapsulate functionality for communication. That way, if you want to implement a different communication library you can easily subclass it and avoid breaking the open-close principle.
https://en.wikipedia.org/wiki/Open/closed_principle
Good luck.

thread overwritten when new socket connects (Server/Client) multithread java

I have to do a cluedo game for Uni, so we have a Server class and Clients that are connecting. For each Client connecting we want to start a own ServerThread with the socket of the Client that is connecting. This Thread just listens to incoming messages and tells the server class to send them back to the client(s).
PROBLEM: each time a new client connects he is overwriting this ServerThread so there is always just one ServerThread and we would like to have one for each Client. We send JSON messages between the Clients and right now the receive message in the ServerThread reads only from the last connected socket. How can i solve this? i added my accept method in the Server i guess the mistake is there but could be anywhere. Thanks for your help!
Mauritius
Server
public void accept() throws IOException{
while(true){
Socket socket = serverSocket.accept();
Runnable r = new ServerThreadHandler(socket);
Thread t = new Thread(r);
t.start();
}
}
ServerThreadHandler:
public class ServerThreadHandler implements Runnable {
static Socket socket=null;
protected User client;
//private static int i;
private static BufferedReader in;
private static OutputStreamWriter out;
public void createUser(String nick, String group, String[] ext) throws IOException{
client = new User(nick, group, ext, null, false, 0, false, socket, socket.getPort());
}
/**
* constructor-Method
* #param socketS
*/
ServerThreadHandler(Socket socketS){
socket = socketS;
}
public void run(){
Server.setThreadList(socket);
in = createReader();
out = createWriter();
//and so on...
}
}
The logic mentioned in you code snippet will definitely create as many threads as the no. of clients that are connecting.
However, the possible reason might be, since the Socket variable in ServerThreadHandler is Static, all subsequent threads being created overwrite the same socket variable causing issue in the previously created thread which is using the socket variable.
You should consider, using non static variable for the Socket in ServerThreadHandler since any runnable class should hold a state and should not be using a static socket.
From what I understood from your question,
createUser method is an instance method of ServerThreadHandler. Hence you must have created the instance of ServerThreadHandler to invoke createUser from another class. Hence you can access the socket variable even if it is an instance variable.
Unfortunately the code has many design flaws:
The quickest fix I can suggest is to remove User class and move everything in the Handler class (or vice verca ? )
also make all your variable non-static
static Socket socket=null;
protected User client;
//private static int i;
private static BufferedReader in;
private static OutputStreamWriter out;
they should be :
Socket socket=null;
protected User client;
//private int i;
private BufferedReader in;
private OutputStreamWriter out;
The Socket member variable should be non-static. Ditto the reader and writer.
Never make a variable static unless you have a really good reason to do so and understand the consequences.

Synchronized object in multiple threads

I have a class that creates multiple threads, each thread gets an socket as parameter in constructor.
I need to synchronize the threads, so that only one thread accesses the sockets streams at given time.
Here is quick draft of what I need:
class MyClass{
Socket socket;
public MyClass() {
socket = new Socket(address, port);
}
void createThread(){
Worker worker = new Worker(socket);
Thread t = new Thread(worker);
t.start();
}
void doStuff(){
InputStream is = socket.getInputStream();
/* ... */
}
}
class Worker implements Runnable{
Socket socket;
public Worker(Socket socket){
this.socket = socket;
}
#Override
public void run() {
InputStream is = socket.getInputStream();
/* ... */
}
}
Now here, potentially multiple threads can access sockets input stream at the same time, which would be very bad.
Now my question is: will synchronized keyword work for this case?
To use basic synchronization you could use the socket as the lock since it's shared by each worker.
public void run() {
synchronized (socket) {
InputStream is = socket.getInputStream();
/* ... */
}
}
If MyClass really needs to access the socket as well, perform the same synchronization in doStuff.
However, you're effectively serializing access to the socket and bypassing the multi-threaded aspect of your application since the lock is held during the entire duration of the run method.

Pre-initializing a pool of worker threads to reuse connection objects (sockets)

I need to build a pool of workers in Java where each worker has its own connected socket; when the worker thread runs, it uses the socket but keeps it open to reuse later. We decided on this approach because the overhead associated with creating, connecting, and destroying sockets on an ad-hoc basis required too much overhead, so we need a method by which a pool of workers are pre-initializaed with their socket connection, ready to take on work while keeping the socket resources safe from other threads (sockets are not thread safe), so we need something along these lines...
public class SocketTask implements Runnable {
Socket socket;
public SocketTask(){
//create + connect socket here
}
public void run(){
//use socket here
}
}
On application startup, we want to initialize the workers and, hopefully, the socket connections somehow too...
MyWorkerPool pool = new MyWorkerPool();
for( int i = 0; i < 100; i++)
pool.addWorker( new WorkerThread());
As work is requested by the application, we send tasks to the worker pool for immediate execution...
pool.queueWork( new SocketTask(..));
Updated with Working Code
Based on helpful comments from Gray and jontejj, I've got the following code working...
SocketTask
public class SocketTask implements Runnable {
private String workDetails;
private static final ThreadLocal<Socket> threadLocal =
new ThreadLocal<Socket>(){
#Override
protected Socket initialValue(){
return new Socket();
}
};
public SocketTask(String details){
this.workDetails = details;
}
public void run(){
Socket s = getSocket(); //gets from threadlocal
//send data on socket based on workDetails, etc.
}
public static Socket getSocket(){
return threadLocal.get();
}
}
ExecutorService
ExecutorService threadPool =
Executors.newFixedThreadPool(5, Executors.defaultThreadFactory());
int tasks = 15;
for( int i = 1; i <= tasks; i++){
threadPool.execute(new SocketTask("foobar-" + i));
}
I like this approach for several reasons...
Sockets are local objects (via ThreadLocal) available to the running tasks, eliminating concurrency issues.
Sockets are created once and kept open, reused
when new tasks get queued, eliminating socket object create/destroy overhead.
One idea would be to put the Sockets in a BlockingQueue. Then whenever you need a Socket your threads can take() from the queue and when they are done with the Socket they put() it back on the queue.
public void run() {
Socket socket = socketQueue.take();
try {
// use the socket ...
} finally {
socketQueue.put(socket);
}
}
This has the added benefits:
You can go back to using the ExecutorService code.
You can separate the socket communication from the processing of the results.
You don't need a 1-to-1 correspondence to processing threads and sockets. But the socket communications may be 98% of the work so maybe no gain.
When you are done and your ExecutorService completes, you can shutdown your sockets by just dequeueing them and closing them.
This does add the additional overhead of another BlockingQueue but if you are doing Socket communications, you won't notice it.
we don't believe ThreadFactory addresses our needs ...
I think you could make this work if you used thread-locals. Your thread factory would create a thread that first opens the socket, stores it in a thread-local, then calls the Runnable arg which does all of the work with the socket, dequeuing jobs from the ExecutorService internal queue. Once it is done the arg.run() method would finish and you could get the socket from the thread-local and close it.
Something like the following. It's a bit messy but you should get the idea.
ExecutorService threadPool =
Executors.newFixedThreadPool(10,
new ThreadFactory() {
public Thread newThread(final Runnable r) {
Thread thread = new Thread(new Runnable() {
public void run() {
openSocketAndStoreInThreadLocal();
// our tasks would then get the socket from the thread-local
r.run();
getSocketFromThreadLocalAndCloseIt();
}
});
return thread;
}
}));
So your tasks would implement Runnable and look like:
public SocketWorker implements Runnable {
private final ThreadLocal<Socket> threadLocal;
public SocketWorker(ThreadLocal<Socket> threadLocal) {
this.threadLocal = threadLocal;
}
public void run() {
Socket socket = threadLocal.get();
// use the socket ...
}
}
I think you should use a ThreadLocal
package com.stackoverflow.q16680096;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Main
{
public static void main(String[] args)
{
ExecutorService pool = Executors.newCachedThreadPool();
int nrOfConcurrentUsers = 100;
for(int i = 0; i < nrOfConcurrentUsers; i++)
{
pool.submit(new InitSocketTask());
}
// do stuff...
pool.submit(new Task());
}
}
package com.stackoverflow.q16680096;
import java.net.Socket;
public class InitSocketTask implements Runnable
{
public void run()
{
Socket socket = SocketPool.get();
// Do initial setup here
}
}
package com.stackoverflow.q16680096;
import java.net.Socket;
public final class SocketPool
{
private static final ThreadLocal<Socket> SOCKETS = new ThreadLocal<Socket>(){
#Override
protected Socket initialValue()
{
return new Socket(); // Pass in suitable arguments here...
}
};
public static Socket get()
{
return SOCKETS.get();
}
}
package com.stackoverflow.q16680096;
import java.net.Socket;
public class Task implements Runnable
{
public void run()
{
Socket socket = SocketPool.get();
// Do stuff with socket...
}
}
Where each thread gets its own socket.

UDP server to handle multiple clients

I created a UDP server. Here's a skeleton
public class UDPserver {
public static void main(String[] args) throws Exception{
while(true){
.... some code ...
packet = new DatagramPacket ( data , data.length, packet.getAddress(), packet.getPort() );
.... some code ...
socket.receive( ... );
}
}
}
Now, i want to make it handle multiple requests, so i checked out that i have to implement Runnable.
public class UDPserver implements Runnable { }
I read that I also need to have a run(). But i don't understand run(). should i put the whole while(true) statement inside run()? what about main()? Can anyone show how to change my code above to handle multiple requests?
thanks
move all the code inside the run method of UDPServer (including the while(true))
In your main method :
UDPServer udpServer = new UDPServer();
udpServer.start();
To make sure that no excpetion won't break your main loop, remember to catch and handle all exceptions that might be rasied inside the while(true) loop
You can also use new thread for each new connection for performing. For example:
class PacketPerforming extends Thread {
DatagramPacket pak;
PacketPerforming(DatagramPacket pak) {
super();
this.pak = pak;
}
public void run() {
// do somethoing with pak
}
}
// in your server thread
while (true) { // i prefered wirte for (;;)
DatagramPacket pak; // take pak object form remote socket
PacketPerforming perform = new PacketPerforming(pak);
perform.start();
}

Categories

Resources