1.what is a lock in core java?

Showing Answers 1 - 4 of 4 Answers

debabrat panda

  • Sep 25th, 2006
 

hi
two memory areas in the Java virtual machine contain data shared by all threads. These are:

  • The heap, which contains all objects
  • The method area, which contains all class variables

If multiple threads need to use the same objects or class variables concurrently, their access to the data must be properly managed. Otherwise, the program will have unpredictable behavior.

To coordinate shared data access among multiple threads, the Java virtual machine associates a lock with each object and class. A lock is like a privilege that only one thread can "possess" at any one time. If a thread wants to lock a particular object or class, it asks the JVM. At some point after the thread asks the JVM for a lock -- maybe very soon, maybe later, possibly never -- the JVM gives the lock to the thread. When the thread no longer needs the lock, it returns it to the JVM. If another thread has requested the same lock, the JVM passes the lock to that thread.

Class locks are actually implemented as object locks. When the JVM loads a class file, it creates an instance of class java.lang.Class. When you lock a class, you are actually locking that class's Class object.

Threads need not obtain a lock to access instance or class variables. If a thread does obtain a lock, however, no other thread can access the locked data until the thread that owns the lock releases it.

lock can be achieved using synchronize key word

  Was this answer useful?  Yes

sheetal

  • Sep 26th, 2006
 

how is it possible for class to obtain a lock? can we use synchronized keyword to a class itself?

  Was this answer useful?  Yes

debabrat panda

  • Sep 26th, 2006
 

hi sheetal

lock concept in not a class level it is object level

Class locks are actually implemented as object locks. When the JVM loads a class file, it creates an instance of class java.lang.Class. When you lock a class, you are actually locking that class's Class object.

deb

  Was this answer useful?  Yes

ajaykjha

  • Oct 15th, 2006
 

The lock is acieved in java by using monitor which is implecitely available to all objects. Once a thread enters into monitor no other thread can enter into the monitor on the same object.

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions