I am making a remote application in java
-
The UDP Server Thread without ds.close() method
public class UDPThreadServer extends Thread { private DatagramSocket datagramSocket; private DatagramPacket datagramPacket; private byte[] data; // the array of bytes which will store data here public UDPThreadServer() { // initialize variables // setup something } public void run() { // overriding run method while(true) { // or while(!ds.isClosed()) datagramSocket.receive(dp); // receive data and assign to byte array } } } -
The Main Program
public class Main { public static UDPThreadServer udpThread; // the udp server running in thread public static void main(String[] args) { udpThread = new UDPThreadServer(); udpThread.start(); // start the thread System.in.read(); } }
Let’s say I have this method
public static void newThread() {
udpThread = new UDPThreadServer(); // destroy and reinitialize thread without calling udpThread.stopUDP();
}
I am curious about Thread Safety in java.
Is it safe to call newThread() method???
It depends upon what you do inside the constructor. Your code doesn’t start a new thread.
If Code that is safe to be called by multiple threads simultaneously then it is thread safe.
Local Variables
Local variables are stored in each thread’s own stack. That means that local variables are never shared between threads.
And hence they are always thread safe.
Local Object References
Local references to objects are a bit different.
The reference itself is not shared. The object referenced however, is not stored in each thread’s local stack.
All objects are stored in the shared heap. If an object created locally never escapes the method it was created in, it is thread safe.
Here is an example of a thread safe local object:
Object Members (fields)
Object members (member variables) are stored on the heap along with the object.
Therefore, if two threads call a method on the same object instance and this method updates object members, the method is not thread safe.
Fields are made safe using any of the below conditions