3

I am trying understand a rationale behind biased locking and making it a default. Since reading this blog post, namely:

"Since most objects are locked by at most one thread during their lifetime, we allow that thread to bias an object toward itself"

I am perplexed... Why would anyone design a synchronized set of methods to be accessed by one thread only? In most cases, people devise certain building blocks specifically for the multi-threaded use-case, and not a single-threaded one. In such cases, EVERY lock aquisition by a thread which is not biased is at the cost of a safepoint, which is a huge overhead! Could someone please help me understand what I am missing in this picture?

Bober02
  • 15,034
  • 31
  • 92
  • 178
  • 3
    Several thread-safe objects (especially in the early days of Java) are used in a single-thread use-cases most of the time (Vector, Hashtable, StringBuffer, for example). Regarding the second question, the paper says: "If another thread tries to acquire a biased object, however, we need to revoke the bias from the original thread. (At this juncture we can either rebias the object or simply revert to normal locking for the remainder of the object's lifetime". – JB Nizet Nov 27 '17 at 21:35
  • See class loading, for example. Of course, this must be implemented in a thread safe way. Still, more than often, almost all classes are loaded by the main thread during the application’s startup or at least a huge number of them is loaded before the class loading lock is acquired by another thread for the first time. – Holger Nov 29 '17 at 17:53

2 Answers2

1

The reason is probably that there are a decent number of libraries and classes that are designed to be thread safe but that are still useful outside of such circumstances. This is especially true of a number of classes that predate the Collections framework. Vector and it's subclasses is a good example. If you also consider that most java programs are not multi threaded it is in most cases an overall improvement to use a biased locking scheme, this is especially true of legacy code where the use of such Classes is all to common.

Diasiare
  • 745
  • 1
  • 6
  • 18
0

You are correct in a way, but there are cases when this is needed, as Holger very correctly points in his comment. There is so-called, the grace period when no biased-locking is attempted at all, so it's not like this will happen all the time. As I last remember looking at the code, it was 5 seconds. To prove this you would need a library that could inspect Java Object's header (jol comes to my mind), since biased locking is hold inside mark word. So only after 5 seconds will the object that held a lock before will be biased towards the same lock.

EDIT

I wanted to write a test for this, but seems like there is one already! Here is the link for it

Eugene
  • 117,005
  • 15
  • 201
  • 306