I'm trying to use String object as a lock (yes, I know it's not recommended - it's only for locks-understanding).
when initializing the lock when creating it, all works well:
code:
public class Action{
String lock = new String("hello");
@Override
public String myAction(long threadId){
synchronized (lock) {
i++;
printToLog("thread " + threadId);
try {
Thread.sleep(100000);
} catch (InterruptedException e) {
printToLog("Thread "+threadId+ " could not sleep "+ e.getMessage() + "\n");
}
printToLog("Thread "+threadId+ " slept well! ");
}
return i+"";
}
private void printToLog(String messege) {
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
//get current date time with Date()
Date date = new Date(System.currentTimeMillis());
logger.info(messege + " at time: "+dateFormat.format(date));
}
}
logs:
[thread 555 at time: 2015/02/18 18:16:03]
[Thread 555 slept well! at time: 2015/02/18 18:17:43]
[thread 557 at time: 2015/02/18 18:17:43]
[Thread 557 slept well! at time: 2015/02/18 18:19:23]
[thread 556 at time: 2015/02/18 18:19:23]
[Thread 556 slept well! at time: 2015/02/18 18:21:03]
but when I initialize the instance member lock within the method, it's as if the synch isn't working.
code:
public class Action{
String lock;
@Override
public String myAction(long threadId){
lock = new String("hello");
synchronized (lock) {
i++;
printToLog("thread " + threadId);
try {
Thread.sleep(100000);
} catch (InterruptedException e) {
printToLog("Thread "+threadId+ " could not sleep "+ e.getMessage() + "\n");
}
printToLog("Thread "+threadId+ " slept well! ");
}
return i+"";
}
private void printToLog(String messege) {
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
//get current date time with Date()
Date date = new Date(System.currentTimeMillis());
logger.info(messege + " at time: "+dateFormat.format(date));
}
}
logs:
[thread 555 at time: 2015/02/18 19:17:35]
[thread 556 at time: 2015/02/18 19:17:40]
[thread 556 at time: 2015/02/18 19:17:41]
[thread 557 at time: 2015/02/18 19:17:44]
[thread 560 at time: 2015/02/18 19:17:48]
[Thread 555 slept well! at time: 2015/02/18 19:19:15]
[Thread 556 slept well! at time: 2015/02/18 19:19:20]
[Thread 556 slept well! at time: 2015/02/18 19:19:21]
[Thread 557 slept well! at time: 2015/02/18 19:19:24]
[Thread 560 slept well! at time: 2015/02/18 19:19:28]
I don't understand what is the metter where I initiate the object? more - it's a string object so anyway it shouldn't be anyway the same reference? what am I misssing?
Edit: Yes, I accidentally swap the code.. that's what happens when you get "your post appears to contain code that is not properly formatted as code" too many times and then find out it was due to log lines :| will fix the swap.