Implementation of the LockSupport class in Java util. concurrent in C #

Source: Internet
Author: User
Tags java util
Java 5 and later provide excellent concurrent libraries util. concurrent,. net lack similar functions. As the hardware system has changed and the multi-core era is approaching, the lack of concurrent class libraries in. NET is obviously out of date. One method is to port java's util. concurrent to C.

The util. concurrent package in java provides LockSupport class. Many key implementations of util. concurrent package need to call LockSupport. To Migrate java's util. concurrent package to C #, The LockSupport class migration is inevitable.

In java, the LockSupport class has the following methods: Public static void park (Object blocker ){
Thread t = Thread. currentThread ();
SetBlocker (t, blocker );
Unsafe. park (false, 0L );
SetBlocker (t, null );
}

When a thread calls LockSupport. park, the thread stops downloading, similar to Object. wait, or System. Threading. Monitor. Wait in. NET. But the problem is that the Object in java. wait and. NET. wait requires a waitObject. This problem has plagued me. For this reason, JDK 6 implements the source code. The solution found at the end is very simple, you do not need to know the underlying implementation source code of JDK.

Public class LockSupport
{
Private static LocalDataStoreSlot slot = Thread. GetNamedDataSlot ("LockSupport. Park ");

Public static void Park (Object blocker)
{
Thread thread = Thread. CurrentThread;
Thread. SetData (slot, blocker );
Lock (thread)
{
Monitor. Wait (thread );
}
}

Public static void Unpark (Thread thread)
{
If (thread = null) return;

Lock (thread)
{
Monitor. Pulse (thread );
}
}
}

The slot is unnecessary, but you can see in the LockSupport code of JDK util. concurrent that using slot (java ThreadLocal) can be used for tracking and debugging.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.