I've programmed a servlet that would call a synchroized method in a threading environment.
In servlet, public void doGet(...) { SMAThreadPost tp = new SMAThreadPost(session, context, input_msg, userip); tp.start(); ... }
In threading class, public synchronized boolean doWrite() { while(...) { <write data into log file> } ... }
public void run() { try { boolean status = doWrite(); sleep(1); } catch(InterruptedException e){} }
However, I found that the data is recorded interactively in log file. For example 1st thread (Data A) and 2nd thread (Data B): Data A Data B Data A Data B Data A Data B
It is supposed that the 1st thread will lock the synchronized method. However, I guess it doesn't work in this case. Is there anything I missed? Pls noted that both thread are running in the same environment.
This looks like the correct result. What synchronization prevents is the method running simultaneously in two different threads on the same object. For instance, if your log output had multiple lines and was not synchronized, you might see lines of one log output for A mixed with one from B. Then, when you added the synchronized keyword, that problem would go away.
What is the result you seek, by the way? If you want all log entries for A to lock out entries from B, then you need to make your own mechanism, with maybe an openLog() method that will then let only one thread log to it until it is closed, or something like that.
However, I want to pinpoint that all "data A"s are recorded within 1st thread and all "data B"s are recorded within 2nd thread.
If 1st thread successfully called the synchronized method "doWrite()" and locked the object. 2nd thread should not be able to write "data B" into the log file until 1st thread finished. Hence "data B" should not be mixed with "data A" in the log file. They should recorded after all "data A"s.
Well, as I said before, you may want to have an open()/close() or lock()/unlock() type of mechanism for your log, otherwise, how does it know when thread A is finished and it can start logging B's input? If you don't mind them mixing, but want to know what is coming from each thread, then include the thread object in the log (so the log may say "[date][time] message from thread [name]: blah, blah, blah."). You would use Thread.currentThread() and Thread.getName().
It looks like you want to apply the readers/writes pattern (Grant - Patterns in Java, Vol 2 a.o., I think), that is you allow read operations, but for writing, you want to wait for all working threads to finish and then execute a write operation. It can be implemented through synchronized blocks, and it seems to me, like bv said, that the result is correct. Hope this help. regards