1 /*
   2  * Copyright (c) 2017, Google and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #ifndef SHARE_VM_PRIMS_JVMTIHEAPSAMPLING_HPP
  26 #define SHARE_VM_PRIMS_JVMTIHEAPSAMPLING_HPP
  27 
  28 // A RAII class that handles transitions from the agent into the VM.
  29 class HeapThreadTransition : StackObj {
  30  private:
  31   JavaThreadState _saved_state;
  32   JavaThread *_jthread;
  33 
  34  public:
  35   // Transitions this thread from the agent (thread_in_native) to the VM.
  36   HeapThreadTransition(Thread *thread) {
  37     if (thread->is_Java_thread()) {
  38       _jthread = static_cast<JavaThread *>(thread);
  39       _saved_state = _jthread->thread_state();
  40       if (_saved_state == _thread_in_native) {
  41         ThreadStateTransition::transition_from_native(_jthread, _thread_in_vm);
  42       } else {
  43         ThreadStateTransition::transition(_jthread,
  44                                           _saved_state,
  45                                           _thread_in_vm);
  46       }
  47     } else {
  48       _jthread = NULL;
  49       _saved_state = _thread_new;
  50     }
  51   }
  52 
  53   // Transitions this thread back to the agent from the VM.
  54   ~HeapThreadTransition() {
  55     if (_jthread != NULL) {
  56       ThreadStateTransition::transition(_jthread, _thread_in_vm, _saved_state);
  57     }
  58   }
  59 };
  60 
  61 #endif // SHARE_VM_PRIMS_JVMTIHEAPSAMPLING_HPP