multithreading - Check the Lock on an object in java -



multithreading - Check the Lock on an object in java -

i want check lock on object of class. utilize thread.holdslock(this) this. right way?

my question how can check if object locked main method , check lock on static methods.

public class checklock { public static void main(string[] args) throws interruptedexception { objectlockclass olc= new objectlockclass(); thread t1=new thread(olc); t1.start(); } } class objectlockclass implements runnable { @override public void run() { boolean islocked = true; int counter=0; synchronized (this) { while (islocked) { seek { thread.sleep(5000); } grab (interruptedexception e) { e.printstacktrace(); } system.out.println("lock object in run : " + thread.holdslock(this)); if (counter==5 ) islocked=false; counter++; } }

the output is:

lock object in run : true lock object in run : true lock object in run : true lock object in run : true lock object in run : true lock object in run : true

how can check object locked main method , check lock on static methods?

an object isn't locked for method. it's locked. period. utility of java's synchronized keyword no 2 threads ever allowed synchronize on same object @ same time.

it doesn't create sense inquire whether other thread has object locked. thread.holdslock(foo) method won't tell that: tells whether calling thread has foo locked. suppose there was method, thread.otherthreadholdslock(foo), , suppose called this:

object foo = ...; if (thread.otherthreadhaslocked(foo)) { dosomething(); } else { dosomethingelse(); }

it doesn't give useful information: code phone call dosomething() foo locked, or foo not locked; , phone call dosomethingelse() foo locked, or foo not locked. there's no guarantee, because thread acquire lock or release lock @ time.

java multithreading locking sleep synchronized

Comments

Popular posts from this blog

model view controller - MVC Rails Planning -

ruby on rails - Devise Logout Error in RoR -

html - Submenu setup with jquery and effect 'fold' -