I have many threads using the below interface ServerMessage
If many threads call the dataChanged() at the same time im
using the SwingUtilities.invokeLater to fire of the job.
My feeling was that this would hold but could not more then
one thread enter the dataChanged() and reassign the runnable
before the SwingUtilities.invokeLater(runnable); is processed?
Maybe i should put a lock on the runnable like this.
synchronized (runnable) {
work...
}
And what about the sO wouldn’t that one also change when next thread enter?
My interface used by many threads
public interface ServerMessage{
public void dataChanged(ServerEventObjects se);
public void logChanged(String txt);
}
This is the interface method
@Override
public void dataChanged(final ServerEventObjects sO) {
Runnable runnable = new Runnable() {
public void run(){
// create new ServerEventObject to avoid making changes to original.
// could clone() it but mongoDb didn't like that
ServerEventObject serverEventObject = new ServerEventObject();
serverEventObject.eventUuid = sO.eventUuid;
serverEventObject.eventUuid = sO.message;
jTextAreaLog.append(serverEventObject.message +"\n" );
JTableModel.add(serverEventObject)
}
};
SwingUtilities.invokeLater(runnable);
}
There is nothing shared between the threads that would allow this kind of behavior. Inside
dataChangedyou create a newRunnableinstance and every thread that invokes the method would do the same. Given your code, no thread would be able to modify the sameRunnableinstance since none of the threads share the same instance.In other words: your implementation of the given interface is thread safe.
Update
I think a good article to read on the topic is The Architecture of the Java Virtual Machine. Since each thread has its own stack, the method invocation, including any local variables, calculations and return values (if any), will be pushed on the calling thread’s stack. Since thread stacks are not shared, then no other thread will be able to "see" the local variables. The only way a thread can "interfere" with each other is if they share something and in this case they’re not sharing anything.