I am writing a small Java class to act a heartbeat for a project. The class is fairly simple. I have a public class called HeartbeatServer.class
that contains to private classes which both implement Runnable
.
The heartbeat and listener thread will both use the same DatagramSocket
which I created outside of the scope of both thread classes and declared it volatile so both threads can access it.
My question is regarding my thread classes. In the thread classes if I call HeartbeatServer.this.serverSocket
what is the scope of this
? My concern is I don't want each thread to use a different version of HeartbeatServer
since I have to bind the DatagramSocket
to a specific IP address and port.
Is what I am doing correct to get the result I am looking for? I want both threads to have access to the same DatagramSocket
that was created by the constructor of the HeartbeatServer
class.
Here is my code.
public volatile DatagramSocket serverSocket;
private Map<String, InetSocketAddress> registeredClients = new HashMap<String, InetSocketAddress>();
public volatile Boolean running = true;
public HeartbeatServer() throws SocketException{
serverSocket = new DatagramSocket(null);
}
** Other methods would go here **
// This is the thread that will send the heartbeats back to the client.
private class HeartbeatThread implements Runnable {
@Override
public void run() {
while (HeartbeatServer.this.running) {
HeartbeatServer.this.sendData();
}
}
}
// This is the thread that will listen for clients connecting to the server.
private class ListenerThread implements Runnable {
@Override
public void run() {
while (HeartbeatServer.this.running) {
HeartbeatServer.this.recieveData();
}
}
}
** NOTE **
My code is not done, so things might not make any sense in the current context.