java - How can a single thread enter a synchronized block twice before exiting twice? -
how can single thread come in synchronized block twice before exiting twice?
in application, i'm implementing singleton pattern , i'm noticing logs showing single thread entering synchronized block twice, exiting twice. so, 2 instances unhappily created. how possible? (i'm particular interested in java)
public class singleton { private static volatile singleton msingleton; private static final object minstancelock = new object(); private singleton() { // basic initialization. } public static singleton getinstance() { if (msingleton == null) { log("before synchronized"); synchronized (minstancelock) { log("in synchronized start"); if (msingleton == null) { msingleton = new singleton(); log("in synchronized, new singleton(), " + msingleton.tostring() + " in thread " + thread.currentthread().getname() + "-" thread.currentthread().getid()); } log("in synchronized end"); } log("after synchronized"); } homecoming msingleton; } }
output, note different objects created, constructor ran through twice (each log in programme outputs current thread id, left out in above code little neater):
before synchronized, in thread id 1 in synchronized start, in thread id 1 before synchronized, in thread id 1 in synchronized start, in thread id 1 // basic initialization. in synchronized, new singleton(), com.example.app.singleton@42453090 in thread: main-1 in synchronized end, in thread id 1 after synchronized, in thread id 1 // basic initialization. in synchronized, new singleton(), com.example.app.singleton@424500b0 in thread: main-1 in synchronized end, in thread id 1 after synchronized, in thread id 1
in regards question, doesn't seem possible. so, if there isn't exact answer, explanation on causing logs show same thread creating 2 different "singletons" great too!
extra notes, in case:
this code running in android app. the code single-threaded, different threads utilizesingleton
. this repeatable every time run code. the timestamps of "before synchronized" , "in synchronized start" same". the timestamps of "in synchronized end" , "after synchronized" pairs off 10ms. it's not apr fools joke lol. i'm not sure other info can provide, please allow me know... more info comments:
log()
output console. little more specifically, calls android.util.log.d()
in android, basic debugging message console. the java object, no other inheritance. java android concurrency synchronization
No comments:
Post a Comment