Markhot oracle что значит снижение конкуренции

Обновлено: 04.07.2024

The DBMS_SHARED_POOL package provides access to the shared pool, which is the shared memory area where cursors and PL/SQL objects are stored. DBMS_SHARED_POOL enables you to display the sizes of objects in the shared pool, and mark them for keeping or not-keeping in order to reduce memory fragmentation.

This chapter contains the following topics:

Using DBMS_SHARED_POOL

Overview

The procedures provided here may be useful when loading large PL/SQL objects. When large PL/SQL objects are loaded, users response time is affected because of the large number of smaller objects that need to be aged out from the shared pool to make room (due to memory fragmentation). In some cases, there may be insufficient memory to load the large objects.

DBMS_SHARED_POOL is also useful for frequently executed triggers. You may want to keep compiled triggers on frequently used tables in the shared pool.

Additionally, DBMS_SHARED_POOL supports sequences. Sequence numbers are lost when a sequence is aged out of the shared pool. DBMS_SHARED_POOL is useful for keeping sequences in the shared pool and thus preventing the loss of sequence numbers.

Operational Notes

To create DBMS_SHARED_POOL , run the DBMSPOOL . SQL script. The PRVTPOOL . PLB script is automatically executed after DBMSPOOL . SQL runs. These scripts are not run by as part of standard database creation.

Summary of DBMS_SHARED_POOL Subprograms

Table 133-1 DBMS_SHARED_POOL Package Subprograms

Sets the aborted request threshold for the shared pool

Keeps an object in the shared pool

Marks a library cache object as a hot object

Purges the named object or specified heap(s) of the object

Shows objects in the shared pool that are larger than the specified size

Unkeeps the named object

Unmarks a library cache object as a hot object

ABORTED_REQUEST_THRESHOLD Procedure

This procedure sets the aborted request threshold for the shared pool.

Table 133-2 ABORTED_REQUEST_THRESHOLD Procedure Parameters

Size, in bytes, of a request which does not try to free unpinned (not "unkeep-ed") memory within the shared pool. The range of threshold_size is 5000 to

An exception is raised if the threshold is not in the valid range.

Usually, if a request cannot be satisfied on the free list, then the RDBMS tries to reclaim memory by freeing objects from the LRU list and checking periodically to see if the request can be fulfilled. After finishing this step, the RDBMS has performed a near equivalent of an ' ALTER SYSTEM FLUSH SHARED_POOL '.

Because this impacts all users on the system, this procedure "localizes" the impact to the process failing to find a piece of shared pool memory of size greater than thresh_hold size. This user gets the 'out of memory' error without attempting to search the LRU list.

KEEP Procedure

This procedure keeps an object in the shared pool. Once an object has been kept in the shared pool, it is not subject to aging out of the pool. This may be useful for frequently used large objects. When large objects are brought into the shared pool, several objects may need to be aged out to create a contiguous area large enough.

Table 133-3 KEEP Procedure Parameters

Name of the object to keep.

The value for this identifier is the concatenation of the address and hash_value columns from the v$sqlarea view. This is displayed by the SIZES procedure.

Currently, TABLE and VIEW objects may not be kept.

(Optional) If this is not specified, then the package assumes that the first parameter is the name of a package/procedure/function and resolves the name.

Set to 'P' or 'p' to fully specify that the input is the name of a package/procedure/function.

Set to 'T' or 't' to specify that the input is the name of a type.

Set to 'R' or 'r' to specify that the input is the name of a trigger.

Set to 'Q' or 'q' to specify that the input is the name of a sequence.

In case the first argument is a cursor address and hash-value, the parameter should be set to any character except 'P' or 'p' or 'Q' or 'q' or 'R' or 'r' or 'T' or 't' .

An exception is raised if the named object cannot be found.

There are two kinds of objects:

PL/SQL objects, triggers, sequences, and types which are specified by name

SQL cursor objects which are specified by a two-part number (indicating a location in the shared pool).

This keeps package HISPACKAGE , owned by SCOTT . The names for PL/SQL objects follow SQL rules for naming objects (for example, delimited identifiers and multibyte names are allowed). A cursor can be kept by DBMS_SHARED_POOL . KEEP('0034CDFF, 20348871','C') , 0034CDFF being the ADDRESS and 20348871 the HASH_VALUE . Note that the complete hexadecimal address must be in the first 8 characters.

MARKHOT Procedure

This procedure marks a library cache object as a hot object.

Table 133-4 MARKHOT Procedure Parameters

User name or the schema to which the object belongs

Name of the object

Number indicating the library cache namespace in which the object is to be searched. Views such as USER_OBJECTS and DBA_OBJECTS reflect the namespace as a number column, as do most dictionary tables such as obj$ .

If TRUE (default), mark the object hot on all OracleRAC instances

16-byte hash value for the object

ORA-06502 : An exception is raised if the named object cannot be found due to incorrect input

ORA-04043 : An exception is raised if the named object cannot be found (bad namespace, or hash input)

PURGE Procedure

This procedure purges the named object or specified heap(s) of the object.

Table 133-5 PURGE Procedure Parameters

Name of the object to purge.

The value for this identifier is the concatenation of the address and hash_value columns from the v$sqlarea view. This is displayed by the SIZES procedure.

Currently, TABLE and VIEW objects may not be purged.

(Optional) If this is not specified, then the package assumes that the first parameter is the name of a package/procedure/function and resolves the name.

Set to 'P' or 'p' to fully specify that the input is the name of a package/procedure/function.

Set to 'T' or 't' to specify that the input is the name of a type.

Set to 'R' or 'r' to specify that the input is the name of a trigger.

Set to 'Q' or 'q' to specify that the input is the name of a sequence.

In case the first argument is a cursor address and hash-value, the parameter should be set to any character except 'P' or 'p' or 'Q' or 'q' or 'R' or 'r' or 'T' or 't'.

Heaps to be purged. For example, if heap 0 and heap 6 are to be purged:

1<<0 | 1<<6 => hex 0x41 => decimal 65, so specify heaps =>65.Default is 1, that is, heap 0 which means the whole object would be purged

User name or the schema to which the object belongs

Name of the object to purge

Parameter is a number indicating the library cache namespace in which the object is to be searched

16-byte hash value for the object

ORA-6570 : An exception is raised if the named object cannot be found

ORA-6570 : An object cannot be purged it marked as permanently kept

All objects supported by the KEEP Procedure are supported for PURGE .

SIZES Procedure

This procedure shows objects in the shared_pool that are larger than the specified size. The name of the object is also given, which can be used as an argument to either the KEEP or UNKEEP calls.

Table 133-6 SIZES Procedure Parameters

Size, in kilobytes, over which an object must be occupying in the shared pool, in order for it to be displayed.

Issue the SQLDBA or SQLPLUS 'SET SERVEROUTPUT ON SIZE XXXXX' command prior to using this procedure so that the results are displayed.

UNKEEP Procedure

This procedure unkeeps the named object.

This procedure may not be supported in the future if automatic mechanisms are implemented to make this unnecessary.

Table 133-7 UNKEEP Procedure Parameters

Name of the object to unkeep. See description of the name object for the KEEP procedure.

See description of the flag parameter for the KEEP procedure.

An exception is raised if the named object cannot be found.

UNMARKHOT Procedure

This procedure unmarks a library cache object as a hot object.

Table 133-8 UNMARKHOT Procedure Parameters

User name or the schema to which the object belongs

Name of the object

Number indicating the library cache namespace in which the object is to be searched

If TRUE (default), unmark the object hot on all Oracle RAC instances

16-byte hash value for the object

ORA-06502 : An exception is raised if the named object cannot be found due to incorrect input

ORA-04043 : An exception is raised if the named object cannot be found (bad namespace, or hash input, or non-existent object)


По нижеприведенным ссылкам Вы можете скачать материалы семинара "Oracle Multitenant Option" который был посвящен практическим аспектам консолидации БД с помощью этой технологии.
Данный семинар проходил в офисе Oracle 29 мая и 26 июня 2014 года.

18 июн. 2014 г.

Markhot и Edition Base Redefinition


Для снижения конкуренции (событие ожидания "library cache: mutex X") за объекты в библиотечном кэше предназначена процедура MARKHOT системного пакета DBMS_SHARED_POOL. Данная процедура производит размножение (создает копии) указанного объекта (пакета, процедуры, курсора и т.д.) в библиотечном кэше, и тем самым снижает конкуренцию за мьютексы.

Недавно, общаясь с одним очень крупным заказчиком, высоконагруженные БД которого работают на больших Hi-End серверах, была затронута тема использования технологии Edition Base Redefinition для безостановочного обновления приложений. Этот заказчик очень активно использует процедуру MARKHOT в своих БД.
Основной вопрос, который волновал заказчика, заключался в поддержке процедурой MARKHOT технологии Edition Base Redefiniton: работает ли вышеописанное размножение объектов в кэше для разных версий (editions) объекта?
В явном виде в процедуре MARKHOT не фигурирует версия объекта (edition в которой он был определен). Давайте разберемся в этом вопросе. Поскольку в данный момент заказчик использует Oracle Database 11.2.0.3, проверим именно на этой версии СУБД.

Создадим отдельного пользователя и новую версию (edition), выдав права на использование этой версии и включив потенциальную версионируемость в вновь созданной схеме: Далее подключимся к БД под вновь созданным пользователем test_markhot и создадим две версии одной и той же процедуры: в версиях ORA$BASE и version_2 соответственно. Далее, для удобства откроем отдельную сессию под пользователем SYS, и проверим наличие нашей процедуры MYPROC в библиотечном кэше помеченной как "горячий" объект, то есть для которой был выполнен вызов DBMS_SHARED_POOL.MARKHOT: Все верно: поскольку мы еще не вызывали процедуру MARKHOT, - процедуры MYPROC в списке "горячих" нет. Для удобства сохраним вышеприведенный запрос в файле hotlist.sql
Находясь под пользователем SYS в версии ORA$BASE пометим нашу нашу процедуру как горячую: Как Вы видите, - наша процедура MYPROC была помечена как горячая. При этом вызов dbms_shared_pool.markhot создал handler на процедуру MYPROC в библиотечном кэше.
Попробуем выполнить процедуру MYPROC в версии ORA$BASE (под владельцем - пользователем test_markhot): и проверим содержимое библиотечного кэша (в другой сессии конечно, - под пользователем SYS): Пока все работает штатно: в кэше были создана копия нашей процедуры. Теперь собственно самая главная часть нашего эксперимента: пометим нашу процедуру как горячую в версии VERSION_2 и проверим содержимое library cache. В кэше появился новый объект помеченный как "горячий"! Вызовем нашу процедуру myproc в версии VERSION_2: и еще раз проверим содержимое library cache: Теперь в кэше началось размножение процедуры myproc новой версии!

Процедура dbms_shared_pool.markhot, которая предназначена для установки метки на горячие объекты в library cache, полностью учитывает версии объектов и ее можно совместно использовать с технологией обновления приложений на лету - Edition Base Redefinition!

Хочу выразить большую благодарность Сергею Томину за помощь в подготовке этого примера!

Применяется в основном для отчетности , для следующих типов задач
1. Запросы рейтингов, первых N
2. Запросы с накопительным итогом
3. Запросы с конструкцией окна
4. Может применятся и для оптимизации запросов

Какие бывают функции в аналитическом, разберём основные
ROW_NUMBER() – номер строки в группе
LAG(f, n,m) –f имя поля, n предыдущее значение в группе, m – знач по умолчанию
LEAD(f, n,m) -f имя поля, n последующее значение в группе, m – знач по умолчанию
FIRST_VALUE(f) – f имя поля, первое значение в группе ,
LAST_VALUE(f) –f имя поля, последнее значение в группе
STD_DEV(f) – f имя поля, значение стандартного распределения в группе
SUM(f) – f имя поля, накопительная сумма по группе
AVG (f)– f имя поля, среднее по группе заданной групп
RANK(f) – f имя поля, относительный ранг записи в группе

Где Партишен - это некоторое количество записей с общими ключами на которую будет распространятся действие Аналитической функции , сортировка внутри партишена осуществляется с помощью order by

Проще всего разобраться с аналитическими функциями на примерах.
Подготовим необходимые данные для демонстрации

Запросы списка лидеров
Первые три сотрудника с самой высокой зарплатой по отделам (партишен по отделу)

Более корректно
Внимание ! Пример демонстрирует отличие rank() от row_number()

По наименованию (партишен по отделу) сортировка по name

Накопительный итог по зарплате

Среднее по зарплате в рамках отдела

Демонстрация работы lag, leed - сотрудник , отдел , зарплата , сотрудник с более большей заплатой (maxsl),
, сотрудник с менее меньшей заплатой чем данный(minsl) в рамках отдела

запрос демонстрирует конструкцию окна в рамках отдела , среднее по зарплате, вычисляется, не только в рамках отдела , но так же и в рамках окна из 3х строк

в запросе используется конструкция окна ROWS BETWEEN N PRECEDING AND CURRENT ROW
то есть, для вычисления среднего avg(sal), считаются 3 предыдущие строки перед текущей строкой

этот запрос демонстрирует применение аналитических функций first_value last_value

The DBMS_SHARED_POOL package provides access to the shared pool, which is the shared memory area where cursors and PL/SQL objects are stored. DBMS_SHARED_POOL enables you to display the sizes of objects in the shared pool, and mark them for keeping or not-keeping in order to reduce memory fragmentation.

This chapter contains the following topics:

Using DBMS_SHARED_POOL

Overview

The procedures provided here may be useful when loading large PL/SQL objects. When large PL/SQL objects are loaded, users response time is affected because of the large number of smaller objects that need to be aged out from the shared pool to make room (due to memory fragmentation). In some cases, there may be insufficient memory to load the large objects.

DBMS_SHARED_POOL is also useful for frequently executed triggers. You may want to keep compiled triggers on frequently used tables in the shared pool.

Additionally, DBMS_SHARED_POOL supports sequences. Sequence numbers are lost when a sequence is aged out of the shared pool. DBMS_SHARED_POOL is useful for keeping sequences in the shared pool and thus preventing the loss of sequence numbers.

Operational Notes

To create DBMS_SHARED_POOL , run the DBMSPOOL . SQL script. The PRVTPOOL . PLB script is automatically executed after DBMSPOOL . SQL runs. These scripts are not run by as part of standard database creation.

Summary of DBMS_SHARED_POOL Subprograms

Table 144-1 DBMS_SHARED_POOL Package Subprograms

Sets the aborted request threshold for the shared pool

Keeps an object in the shared pool

Marks a library cache object as a hot object

Purges the named object or specified heap(s) of the object

Shows objects in the shared pool that are larger than the specified size

Unkeeps the named object

Unmarks a library cache object as a hot object

ABORTED_REQUEST_THRESHOLD Procedure

This procedure sets the aborted request threshold for the shared pool.

Table 144-2 ABORTED_REQUEST_THRESHOLD Procedure Parameters

Size, in bytes, of a request which does not try to free unpinned (not "unkeep-ed") memory within the shared pool. The range of threshold_size is 5000 to

An exception is raised if the threshold is not in the valid range.

Usually, if a request cannot be satisfied on the free list, then the RDBMS tries to reclaim memory by freeing objects from the LRU list and checking periodically to see if the request can be fulfilled. After finishing this step, the RDBMS has performed a near equivalent of an ' ALTER SYSTEM FLUSH SHARED_POOL '.

Because this impacts all users on the system, this procedure "localizes" the impact to the process failing to find a piece of shared pool memory of size greater than thresh_hold size. This user gets the 'out of memory' error without attempting to search the LRU list.

KEEP Procedure

This procedure keeps an object in the shared pool. Once an object has been kept in the shared pool, it is not subject to aging out of the pool. This may be useful for frequently used large objects. When large objects are brought into the shared pool, several objects may need to be aged out to create a contiguous area large enough.

Table 144-3 KEEP Procedure Parameters

Name of the object to keep.

The value for this identifier is the concatenation of the address and hash_value columns from the v$sqlarea view. This is displayed by the SIZES procedure.

Currently, TABLE and VIEW objects may not be kept.

(Optional) If this is not specified, then the package assumes that the first parameter is the name of a package/procedure/function and resolves the name.

Set to 'P' or 'p' to fully specify that the input is the name of a package/procedure/function.

Set to 'T' or 't' to specify that the input is the name of a type.

Set to 'R' or 'r' to specify that the input is the name of a trigger.

Set to 'Q' or 'q' to specify that the input is the name of a sequence.

In case the first argument is a cursor address and hash-value, the parameter should be set to any character except 'P' or 'p' or 'Q' or 'q' or 'R' or 'r' or 'T' or 't' .

An exception is raised if the named object cannot be found.

There are two kinds of objects:

PL/SQL objects, triggers, sequences, and types which are specified by name

SQL cursor objects which are specified by a two-part number (indicating a location in the shared pool).

This keeps package HISPACKAGE , owned by SCOTT . The names for PL/SQL objects follow SQL rules for naming objects (for example, delimited identifiers and multibyte names are allowed). A cursor can be kept by DBMS_SHARED_POOL . KEEP('0034CDFF, 20348871','C') , 0034CDFF being the ADDRESS and 20348871 the HASH_VALUE . Note that the complete hexadecimal address must be in the first 8 characters.

MARKHOT Procedure

This procedure marks a library cache object as a hot object.

Table 144-4 MARKHOT Procedure Parameters

User name or the schema to which the object belongs

Name of the object

Number indicating the library cache namespace in which the object is to be searched. Views, such as USER_OBJECTS and DBA_OBJECTS , reflect the namespace as a number column, as do most dictionary tables such as OBJ$ .

If TRUE (default), mark the object hot on all Oracle RAC instances

16-byte hash value for the object

ORA-06502 : An exception is raised if the named object cannot be found due to incorrect input

ORA-04043 : An exception is raised if the named object cannot be found (bad namespace, or hash input)

If a package or type's specification is marked hot or unhot, then the corresponding package or type body will be implicitly marked as hot or unhot.

PURGE Procedure

This procedure purges the named object or specified heap(s) of the object.

Table 144-5 PURGE Procedure Parameters

Name of the object to purge.

The value for this identifier is the concatenation of the address and hash_value columns from the v$sqlarea view. This is displayed by the SIZES procedure.

Currently, TABLE and VIEW objects may not be purged.

(Optional) If this is not specified, then the package assumes that the first parameter is the name of a package/procedure/function and resolves the name.

Set to 'P' or 'p' to fully specify that the input is the name of a package/procedure/function.

Set to 'T' or 't' to specify that the input is the name of a type.

Set to 'R' or 'r' to specify that the input is the name of a trigger.

Set to 'Q' or 'q' to specify that the input is the name of a sequence.

In case the first argument is a cursor address and hash-value, the parameter should be set to any character except 'P' or 'p' or 'Q' or 'q' or 'R' or 'r' or 'T' or 't'.

Heaps to be purged. For example, if heap 0 and heap 6 are to be purged:

1<<0 | 1<<6 => hex 0x41 => decimal 65, so specify heaps =>65.Default is 1, that is, heap 0 which means the whole object would be purged

User name or the schema to which the object belongs

Name of the object to purge

Parameter is a number indicating the library cache namespace in which the object is to be searched

16-byte hash value for the object

ORA-6570 : An exception is raised if the named object cannot be found

ORA-6570 : An object cannot be purged it marked as permanently kept

All objects supported by the KEEP Procedure are supported for PURGE .

SIZES Procedure

This procedure shows objects in the shared_pool that are larger than the specified size. The name of the object is also given, which can be used as an argument to either the KEEP or UNKEEP calls.

Table 144-6 SIZES Procedure Parameters

Size, in kilobytes, over which an object must be occupying in the shared pool, in order for it to be displayed.

Issue the SQLDBA or SQLPLUS 'SET SERVEROUTPUT ON SIZE XXXXX' command prior to using this procedure so that the results are displayed.

UNKEEP Procedure

This procedure unkeeps the named object.

This procedure may not be supported in the future if automatic mechanisms are implemented to make this unnecessary.

Table 144-7 UNKEEP Procedure Parameters

Name of the object to unkeep. See description of the name object for the KEEP procedure.

See description of the flag parameter for the KEEP procedure.

ORA-06502 : An exception is raised if the named object cannot be found

UNMARKHOT Procedure

This procedure unmarks a library cache object as a hot object.

Table 144-8 UNMARKHOT Procedure Parameters

User name or the schema to which the object belongs

Name of the object

Number indicating the library cache namespace in which the object is to be searched

If TRUE (default), unmark the object hot on all Oracle RAC instances

16-byte hash value for the object

ORA-06502 : An exception is raised if the named object cannot be found due to incorrect input

ORA-04043 : An exception is raised if the named object cannot be found (bad namespace, or hash input, or non-existent object)

If a package or type's specification is marked hot or unhot, then the corresponding package or type body will be implicitly marked as hot or unhot.

Читайте также: