I am having a code this way,
public int handle_refresh(Data mmsg) throws Exception {
String custId = mmsg.getCustomerId();
CustomerThread t = custMap.get(mmsg.getCustomerId());
if (t == null || !t.isAlive()) {
t = (CustomerThread) context.getBean("custT");
t.initThread(mmsg.getCustomerId(), mmsg.getCustomerId(), mmsg.getMessageBody());
custSMap.put(mmsg.getCustomerId(), t);
t.createBufferThread();
t.start();
t.initStreaming();
}
synchronized (t) {
if (null != t) {
ret = t.addSymbols(mmsg);
}
}
return ret;
}
}
Here CustomerThread is checked in custMap,
Map custMap= new CustomerThread ();
if thread is there in custMap
1) then read spring appilcation context and get it. t = (CustomerThread) context.getBean("custT");
2) In initThread method set the name of the thread uniquely for each customer. t.initThread(mmsg.getCustomerId(), mmsg.getCustomerId(), mmsg.getMessageBody());
3) then put the newly created thread in to map custMap. custSMap.put(mmsg.getCustomerId(), t);
4) then in createBufferThread data is setting into cache.. t.createBufferThread();
5) then start the thread newly and then get data from db. t.start();
6) set the db connections
if thread is not there in custMap
1) synchronized (t) .
2) call t.addSymbols() method.
My questions are…
1) Here does the first if block executes only first time and if once thread is created always synchronized (t) is executed?
I mean all the above 1 to 6 steps in if block are executed only once?
2) then what does synchronized (t) does?
It looks to me that
sychronized (t)is protecting theaddSymbolsmethod to make it thread-safe. Calls to this method are adding symbols, I assume, to some data structure within thetthread. It may be that other methods in that thread aresynchronizedwhich would mean that it would be locking on theThreadinstance. That’s whatsychronized (t)is doing here.But this is an extremely ugly way of adding thread-safety. The
addSymbols(...)method should itself lock on a lock object or, if necessary, be asynchronizedmethod. A class should be responsible for it’s own locking and not require the caller to do something.Couple other comments about your code:
The above code seems to be getting a thread instance from Spring. This is typically a singleton unless the “custT” bean is some sort of thread-factory. If it is not a factory bean then you are going to be getting the same thread-object for each call to your
handle_refreshmethod and reinitializing it. This is most likely not what you want.If
twasnullthen thesynchronizedline would throw a NPE. You don’t need thenullcheck inside ofsynchronized.If the
handle_refresh(...)method is called from multiple threads then you need to make sure that thecustMapis properly synchronized as well.