国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

ホームページ Java &#&チュートリアル Java での同期の同時実行性の分析

Java での同期の同時実行性の分析

Jan 18, 2017 pm 03:18 PM

Java プログラミング言語

java は、クロスプラットフォームのアプリケーション ソフトウェアを作成できるオブジェクト指向プログラミング言語です。これは、1995 年 5 月に Sun Microsystems によって開始された Java プログラミング言語および Java プラットフォームです (つまり、JavaEE (j2ee)、一般名)。 JavaME(j2me)、JavaSE(j2se))。


JDK では、主に同期のための synchronzied の解析はあまりありません。 jvm で synchronizer.cpp のソース コードを分析してみましょう。jvm ソース コードは http://hg.openjdk.java.net/

synchronzier.cpp からダウンロードできます。ディレクトリは hotspot-9646293b9637srcsharevmruntime

です。最下層 JNI を使用して ObjectMonitor を呼び出し、スレッドの wait()、notify()、notifyAll() などを?qū)g裝します。

概要については、以下のホットスポット ソース コード (C++ で記述) を參照してください。


wait()

// NOTE: must use heavy weight monitor to handle wait()
void ObjectSynchronizer::wait(Handle obj, jlong millis, TRAPS) {
  if (UseBiasedLocking) {
    BiasedLocking::revoke_and_rebias(obj, false, THREAD);
    assert(!obj->mark()->has_bias_pattern(), "biases should be revoked by now");
  }
  if (millis < 0) {//時間小于0會拋出異常
    TEVENT (wait - throw IAX) ;
    THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), "timeout value is negative");
  }
  ObjectMonitor* monitor = ObjectSynchronizer::inflate(THREAD, obj());
  DTRACE_MONITOR_WAIT_PROBE(monitor, obj(), THREAD, millis);

  //調(diào)用了ObjectMonitor中的wait
  monitor->wait(millis, true, THREAD);

  /* This dummy call is in place to get around dtrace bug 6254741.  Once
     that&#39;s fixed we can uncomment the following line and remove the call */
  // DTRACE_MONITOR_PROBE(waited, monitor, obj(), THREAD);
  dtrace_waited_probe(monitor, obj, THREAD);
}</span>

ObjectMonitor::wait()

// Note: a subset of changes to ObjectMonitor::wait()
// will need to be replicated in complete_exit above
void ObjectMonitor::wait(jlong millis, bool interruptible, TRAPS) {
   Thread * const Self = THREAD ;
   assert(Self->is_Java_thread(), "Must be Java thread!");
   JavaThread *jt = (JavaThread *)THREAD;

   DeferredInitialize () ;

   // Throw IMSX or IEX.
   CHECK_OWNER();

   // check for a pending interrupt 是否有中斷信號
   if (interruptible && Thread::is_interrupted(Self, true) && !HAS_PENDING_EXCEPTION) {
     // post monitor waited event.  Note that this is past-tense, we are done waiting.
     if (JvmtiExport::should_post_monitor_waited()) {
        // Note: &#39;false&#39; parameter is passed here because the
        // wait was not timed out due to thread interrupt.
        JvmtiExport::post_monitor_waited(jt, this, false);
     }
     TEVENT (Wait - Throw IEX) ;
     THROW(vmSymbols::java_lang_InterruptedException());
     return ;
   }
   TEVENT (Wait) ;

   assert (Self->_Stalled == 0, "invariant") ;
   Self->_Stalled = intptr_t(this) ;
   //設(shè)置線程的監(jiān)視鎖
   jt->set_current_waiting_monitor(this);

   // create a node to be put into the queue
   // Critically, after we reset() the event but prior to park(), we must check
   // for a pending interrupt.
   //添加一個節(jié)點(diǎn)放入到等待隊(duì)列中
   ObjectWaiter node(Self);
   node.TState = ObjectWaiter::TS_WAIT ;
   Self->_ParkEvent->reset() ;
   OrderAccess::fence();          // ST into Event; membar ; LD interrupted-flag

   // Enter the waiting queue, which is a circular doubly linked list in this case
   // but it could be a priority queue or any data structure.
   // _WaitSetLock protects the wait queue.  Normally the wait queue is accessed only
   // by the the owner of the monitor *except* in the case where park()
   // returns because of a timeout of interrupt.  Contention is exceptionally rare
   // so we use a simple spin-lock instead of a heavier-weight blocking lock.
   //添加元素c++使用同步的方式,獲取鎖
   Thread::SpinAcquire (&_WaitSetLock, "WaitSet - add") ;
   //添加節(jié)點(diǎn)
   AddWaiter (&node) ;
   //釋放鎖
   Thread::SpinRelease (&_WaitSetLock) ;

   if ((SyncFlags & 4) == 0) {
      _Responsible = NULL ;
   }
   intptr_t save = _recursions; // record the old recursion count
   //增加等待線程數(shù)
   _waiters++;                  // increment the number of waiters
   _recursions = 0;             // set the recursion level to be 1
   exit (Self) ;                    // exit the monitor
   guarantee (_owner != Self, "invariant") ;

   // As soon as the ObjectMonitor&#39;s ownership is dropped in the exit()
   // call above, another thread can enter() the ObjectMonitor, do the
   // notify(), and exit() the ObjectMonitor. If the other thread&#39;s
   // exit() call chooses this thread as the successor and the unpark()
   // call happens to occur while this thread is posting a
   // MONITOR_CONTENDED_EXIT event, then we run the risk of the event
   // handler using RawMonitors and consuming the unpark().
   //
   // To avoid the problem, we re-post the event. This does no harm
   // even if the original unpark() was not consumed because we are the
   // chosen successor for this monitor.
   if (node._notified != 0 && _succ == Self) {
      node._event->unpark();
   }

   // The thread is on the WaitSet list - now park() it.
   // On MP systems it&#39;s conceivable that a brief spin before we park
   // could be profitable.
   //
   // TODO-FIXME: change the following logic to a loop of the form
   //   while (!timeout && !interrupted && _notified == 0) park()

   int ret = OS_OK ;
   int WasNotified = 0 ;
   { // State transition wrappers
     OSThread* osthread = Self->osthread();
     OSThreadWaitState osts(osthread, true);
     {
       ThreadBlockInVM tbivm(jt);
       // Thread is in thread_blocked state and oop access is unsafe.
       jt->set_suspend_equivalent();

       if (interruptible && (Thread::is_interrupted(THREAD, false) || HAS_PENDING_EXCEPTION)) {
           // Intentionally empty
       } else
       if (node._notified == 0) {
         if (millis <= 0) {
            Self->_ParkEvent->park () ;
         } else {
            ret = Self->_ParkEvent->park (millis) ;
         }
       }

       // were we externally suspended while we were waiting?
       if (ExitSuspendEquivalent (jt)) {
          // TODO-FIXME: add -- if succ == Self then succ = null.
          jt->java_suspend_self();
       }

     } // Exit thread safepoint: transition _thread_blocked -> _thread_in_vm


     // Node may be on the WaitSet, the EntryList (or cxq), or in transition
     // from the WaitSet to the EntryList.
     // See if we need to remove Node from the WaitSet.
     // We use double-checked locking to avoid grabbing _WaitSetLock
     // if the thread is not on the wait queue.
     //
     // Note that we don&#39;t need a fence before the fetch of TState.
     // In the worst case we&#39;ll fetch a old-stale value of TS_WAIT previously
     // written by the is thread. (perhaps the fetch might even be satisfied
     // by a look-aside into the processor&#39;s own store buffer, although given
     // the length of the code path between the prior ST and this load that&#39;s
     // highly unlikely).  If the following LD fetches a stale TS_WAIT value
     // then we&#39;ll acquire the lock and then re-fetch a fresh TState value.
     // That is, we fail toward safety.

     if (node.TState == ObjectWaiter::TS_WAIT) {
         Thread::SpinAcquire (&_WaitSetLock, "WaitSet - unlink") ;
         if (node.TState == ObjectWaiter::TS_WAIT) {
            DequeueSpecificWaiter (&node) ;       // unlink from WaitSet
            assert(node._notified == 0, "invariant");
            node.TState = ObjectWaiter::TS_RUN ;
         }
         Thread::SpinRelease (&_WaitSetLock) ;
     }

     // The thread is now either on off-list (TS_RUN),
     // on the EntryList (TS_ENTER), or on the cxq (TS_CXQ).
     // The Node&#39;s TState variable is stable from the perspective of this thread.
     // No other threads will asynchronously modify TState.
     guarantee (node.TState != ObjectWaiter::TS_WAIT, "invariant") ;
     OrderAccess::loadload() ;
     if (_succ == Self) _succ = NULL ;
     WasNotified = node._notified ;

     // Reentry phase -- reacquire the monitor.
     // re-enter contended monitor after object.wait().
     // retain OBJECT_WAIT state until re-enter successfully completes
     // Thread state is thread_in_vm and oop access is again safe,
     // although the raw address of the object may have changed.
     // (Don&#39;t cache naked oops over safepoints, of course).

     // post monitor waited event. Note that this is past-tense, we are done waiting.
     if (JvmtiExport::should_post_monitor_waited()) {
       JvmtiExport::post_monitor_waited(jt, this, ret == OS_TIMEOUT);
     }
     OrderAccess::fence() ;

     assert (Self->_Stalled != 0, "invariant") ;
     Self->_Stalled = 0 ;

     assert (_owner != Self, "invariant") ;
     ObjectWaiter::TStates v = node.TState ;
     if (v == ObjectWaiter::TS_RUN) {
         enter (Self) ;
     } else {
         guarantee (v == ObjectWaiter::TS_ENTER || v == ObjectWaiter::TS_CXQ, "invariant") ;
         ReenterI (Self, &node) ;
         node.wait_reenter_end(this);
     }

     // Self has reacquired the lock.
     // Lifecycle - the node representing Self must not appear on any queues.
     // Node is about to go out-of-scope, but even if it were immortal we wouldn&#39;t
     // want residual elements associated with this thread left on any lists.
     guarantee (node.TState == ObjectWaiter::TS_RUN, "invariant") ;
     assert    (_owner == Self, "invariant") ;
     assert    (_succ != Self , "invariant") ;
   } // OSThreadWaitState()

   jt->set_current_waiting_monitor(NULL);

   guarantee (_recursions == 0, "invariant") ;
   _recursions = save;     // restore the old recursion count
   _waiters--;             // decrement the number of waiters

   // Verify a few postconditions
   assert (_owner == Self       , "invariant") ;
   assert (_succ  != Self       , "invariant") ;
   assert (((oop)(object()))->mark() == markOopDesc::encode(this), "invariant") ;

   if (SyncFlags & 32) {
      OrderAccess::fence() ;
   }

   // check if the notification happened
   if (!WasNotified) {
     // no, it could be timeout or Thread.interrupt() or both
     // check for interrupt event, otherwise it is timeout
     if (interruptible && Thread::is_interrupted(Self, true) && !HAS_PENDING_EXCEPTION) {
       TEVENT (Wait - throw IEX from epilog) ;
       THROW(vmSymbols::java_lang_InterruptedException());
     }
   }

   // NOTE: Spurious wake up will be consider as timeout.
   // Monitor notify has precedence over thread interrupt.
}</span>

ObjectMonitor::notify()

void ObjectMonitor::notify(TRAPS) {
  CHECK_OWNER();
  if (_WaitSet == NULL) {
     TEVENT (Empty-Notify) ;
     return ;
  }
  DTRACE_MONITOR_PROBE(notify, this, object(), THREAD);

  int Policy = Knob_MoveNotifyee ;

  Thread::SpinAcquire (&_WaitSetLock, "WaitSet - notify") ;
  ObjectWaiter * iterator = DequeueWaiter() ;
  // ...
  //省略中間代碼
  //...
        ParkEvent * ev = iterator->_event ;
        //設(shè)置狀態(tài)
        iterator->TState = ObjectWaiter::TS_RUN ;
        OrderAccess::fence() ;
        //釋放鎖
        ev->unpark() ;
     }

     if (Policy < 4) {
       iterator->wait_reenter_begin(this);
     }
  }</span>
また、notifyAll()、SimpleEnter()、SimpeExit() もあります。コード。

上記は Java 同時実行性の同期分析の內(nèi)容です。さらに関連する內(nèi)容については、PHP 中國語 Web サイト (www.miracleart.cn) に注目してください。

このウェブサイトの聲明
この記事の內(nèi)容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰屬します。このサイトは、それに相當(dāng)する法的責(zé)任を負(fù)いません。盜作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡(luò)ください。

ホットAIツール

Undress AI Tool

Undress AI Tool

脫衣畫像を無料で

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード寫真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

寫真から衣服を削除するオンライン AI ツール。

Clothoff.io

Clothoff.io

AI衣類リムーバー

Video Face Swap

Video Face Swap

完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

ホットツール

メモ帳++7.3.1

メモ帳++7.3.1

使いやすく無料のコードエディター

SublimeText3 中國語版

SublimeText3 中國語版

中國語版、とても使いやすい

ゼンドスタジオ 13.0.1

ゼンドスタジオ 13.0.1

強(qiáng)力な PHP 統(tǒng)合開発環(huán)境

ドリームウィーバー CS6

ドリームウィーバー CS6

ビジュアル Web 開発ツール

SublimeText3 Mac版

SublimeText3 Mac版

神レベルのコード編集ソフト(SublimeText3)

JDBCを使用してJavaのトランザクションを処理する方法は? JDBCを使用してJavaのトランザクションを処理する方法は? Aug 02, 2025 pm 12:29 PM

JDBCトランザクションを正しく処理するには、最初に自動コミットモードをオフにし、次に複數(shù)の操作を?qū)g行し、結(jié)果に応じて最終的にコミットまたはロールバックする必要があります。 1。CONN.SETAUTOCOMMIT(FALSE)を呼び出して、トランザクションを開始します。 2。挿入や更新など、複數(shù)のSQL操作を?qū)g行します。 3。すべての操作が成功した場合はconn.commit()を呼び出し、データの一貫性を確保するために例外が発生した場合はconn.rollback()を呼び出します。同時に、リソースを使用してリソースを管理し、例外を適切に処理し、接続を密接に接続するために、接続の漏れを避けるために使用する必要があります。さらに、接続プールを使用してセーブポイントを設(shè)定して部分的なロールバックを達(dá)成し、パフォーマンスを改善するためにトランザクションを可能な限り短く保つことをお勧めします。

Javaでカレンダーを操作する方法は? Javaでカレンダーを操作する方法は? Aug 02, 2025 am 02:38 AM

Java.Timeパッケージのクラスを使用して、古い日付とカレンダーのクラスを置き換えます。 2。LocalDate、LocalDateTime、LocalTimeを通じて現(xiàn)在の日付と時刻を取得します。 3。of()メソッドを使用して特定の日付と時刻を作成します。 4.プラス/マイナスメソッドを使用して、時間を不正に増加させて短縮します。 5. ZonedDateTimeとZoneIDを使用して、タイムゾーンを処理します。 6。DateTimeFormatterを介したフォーマットおよび解析の文字列。 7.インスタントを使用して、必要に応じて古い日付型と互換性があります。現(xiàn)代のJavaでの日付処理は、java.timeapiを使用することを優(yōu)先する必要があります。

Javaフレームワークの比較:Spring Boot vs Quarkus vs Micronaut Javaフレームワークの比較:Spring Boot vs Quarkus vs Micronaut Aug 04, 2025 pm 12:48 PM

Pre-formanceTartuptimeMemoryusage、quarkusandmicronautleadduetocopile-timeprocessingingandgraalvsupport、withquarkusoftentylightbetterine serverlessシナリオ。

ネットワークポートとファイアウォールの理解 ネットワークポートとファイアウォールの理解 Aug 01, 2025 am 06:40 AM

ネットワークポートアンドファイアワルクトグテルトエナブルコマニケーションwhiledensuringsecurity.1.networksarevirtualendpointsnumbered0–655 35、withwell-knownportslike80(http)、443(https)、22(ssh)、および25(smtp)識別pecificservices.2.portsoperateovertcp(信頼できる、c

Garbage CollectionはJavaでどのように機(jī)能しますか? Garbage CollectionはJavaでどのように機(jī)能しますか? Aug 02, 2025 pm 01:55 PM

JavaのGarbage Collection(GC)は、メモリを自動的に管理するメカニズムであり、到達(dá)不可能なオブジェクトを取り戻すことでメモリ漏れのリスクを軽減します。 1.GCルートオブジェクトからのオブジェクトのアクセシビリティ(スタック変數(shù)、アクティブスレッド、靜的フィールドなど)、および到達(dá)不可能なオブジェクトはゴミとしてマークされています。 2。マーククリアリングアルゴリズムに基づいて、すべての到達(dá)可能なオブジェクトをマークし、マークのないオブジェクトをクリアします。 3.世代の収集戦略を採用する:新世代(Eden、S0、S1)は頻繁にMinorGCを?qū)g行します。高齢者のパフォーマンスは少なくなりますが、MajorGCを?qū)g行するのに時間がかかります。 Metaspaceはクラスメタデータを保存します。 4。JVMはさまざまなGCデバイスを提供します。SerialGCは小さなアプリケーションに適しています。 ParallelGCはスループットを改善します。 CMSが減少します

ユーザーデータにHTML「入力」タイプを使用します ユーザーデータにHTML「入力」タイプを使用します Aug 03, 2025 am 11:07 AM

適切なHTMLinputタイプを選択すると、データの精度を向上させ、ユーザーエクスペリエンスを向上させ、使いやすさを向上させることができます。 1.テキスト、電子メール、電話、番號、日付など、データ型に従って対応する入力タイプを選択します。 2。HTML5を使用して、より直感的な相互作用方法を提供できるURL、色、範(fàn)囲、検索などの新しいタイプを追加します。 3.プレースホルダーと必要な屬性を使用して、フォームフィリングの効率と精度を改善しますが、プレースホルダーがラベルを置き換えることはできないことに注意してください。

Javaビルドツールの比較:Maven vs. Gradle Javaビルドツールの比較:Maven vs. Gradle Aug 03, 2025 pm 01:36 PM

gradleisthebetterchoiceformostnewprojectoitssuperorfficability、performance、andmoderntoolingsupport.1.gradle’sgroovy/kotlindslismoreconciseandexpressiveethanmaven’sverboseml.2.gradleorformsmavenbenbumebutedwitedwitedwitedspedexは

説明された延期聲明の例で進(jìn)みます 説明された延期聲明の例で進(jìn)みます Aug 02, 2025 am 06:26 AM

Deferは、クリーニングリソースなど、関數(shù)が戻る前に指定された操作を?qū)g行するために使用されます。パラメーターは、延期時にすぐに評価され、関數(shù)は最後のファーストアウト(LIFO)の順に実行されます。 1.複數(shù)の債務(wù)は、宣言の逆の順序で実行されます。 2.ファイルの閉鎖などの安全なクリーニングに一般的に使用されます。 3。指定された返品値を変更できます。 4.回復(fù)に適したパニックが発生した場合でも実行されます。 5。リソースの漏れを防ぐために、ループで延期の亂用を避けます。正しい使用により、コードのセキュリティと読みやすさが向上します。

See all articles