Sub topic 8
Package state and how long it lives
This chapter explains what package state is and where it is stored. It also covers when state is created, when it is lost, and what that means for the code you write. It assumes you can write packages with a specification and a body, and that you know PL/SQL variables, transactions (COMMIT and ROLLBACK) and basic exception handling.
What counts as package state
Package state is the set of values held by package-level variables, collections and open cursors. A variable declared in the specification is public. A variable declared in the body, outside any subprogram, is private. Either way, it is package state.
A variable declared inside a subprogram is different. It is created on each call and discarded when the call returns. Package-level variables are created once for the session and kept.
Constants do not hold state, because their values never change. A package that contains only constants and subprograms without package-level variables is called stateless. This matters for recompilation, covered later in this chapter.
State lives in the session
Oracle creates a separate copy of the package's state for each database session. The copy is created the first time the session references the package. That first reference might be a procedure call, a function call or a read of a public variable. At that moment Oracle:
- Allocates memory for the package-level variables.
- Assigns any initial values from the declarations, such as
g_count PLS_INTEGER := 0. - Runs the initialization section, if the body has one. The next chapter covers it.
After that, every call from the same session sees and changes the same copy.
Here is a small package that records page visits.
CREATE OR REPLACE PACKAGE visit_log AS
PROCEDURE record_visit(p_page IN VARCHAR2);
FUNCTION visit_count RETURN PLS_INTEGER;
FUNCTION last_page RETURN VARCHAR2;
END visit_log;
/
CREATE OR REPLACE PACKAGE BODY visit_log AS
g_count PLS_INTEGER := 0;
g_last_page VARCHAR2(100);
PROCEDURE record_visit(p_page IN VARCHAR2) IS
BEGIN
g_count := g_count + 1;
g_last_page := p_page;
END record_visit;
FUNCTION visit_count RETURN PLS_INTEGER IS
BEGIN
RETURN g_count;
END visit_count;
FUNCTION last_page RETURN VARCHAR2 IS
BEGIN
RETURN g_last_page;
END last_page;
END visit_log;
/Run two separate anonymous blocks in the same session:
SET SERVEROUTPUT ON
BEGIN
visit_log.record_visit('/home');
visit_log.record_visit('/pricing');
END;
/
BEGIN
DBMS_OUTPUT.PUT_LINE(visit_log.visit_count || ' visits, last: ' || visit_log.last_page);
END;
/The second block prints 2 visits, last: /pricing. The first block has finished, but the values stayed in the session. A second session that runs only the second block prints 0 visits, last: , because it gets its own fresh copy.
The package code is stored once in the database and shared. The data is not shared.
Transactions do not affect state
Package variables are ordinary memory in your session. They are not part of any transaction. COMMIT does not save them, and ROLLBACK does not restore them.
BEGIN
visit_log.record_visit('/checkout');
ROLLBACK;
DBMS_OUTPUT.PUT_LINE(visit_log.visit_count);
END;
/If the session already had a count of 2, this prints 3. The rollback undoes table changes only. If your package keeps a cached copy of table data in a variable, a rollback can leave the cache out of step with the table. When you cache data this way, decide how and when the cache is refreshed.
What ends or resets state
State disappears in a small number of ways. The table lists them.
| Event | Effect on state |
|---|---|
| Session ends (disconnect, logoff, kill) | All state is freed. |
| `COMMIT` or `ROLLBACK` | No effect. |
| Another session calls the package | No effect on your copy. |
| Package body recompiled | Your copy is discarded. The next call raises ORA-04068. |
| `DBMS_SESSION.RESET_PACKAGE` called | Your copy is freed when the current top-level call finishes. |
| Unhandled exception in a subprogram | Variables keep any changes already made. |
The last row is easy to forget. If a procedure updates g_count and then fails with an exception, the update to g_count stays. Only the SQL changes made by that call are rolled back, and only when the exception propagates to the caller as a statement-level rollback.
Recompilation and ORA-04068
Suppose session A has used visit_log, and then a developer in another session recompiles the body. Session A's in-memory state no longer matches the stored code. On its next call, session A gets:
ORA-04068: existing state of packages has been discarded
ORA-04061: existing state of package body "APP.VISIT_LOG" has been invalidated
ORA-06508: PL/SQL: could not find program unit being called: "APP.VISIT_LOG"Oracle has already discarded the old state by the time you see the error. The call that raised the error did not run. If you repeat it, it succeeds against a freshly instantiated package, and all values are back at their initial settings.
This is the main operational cost of package state. The fix is not to avoid state, but to know where it matters:
- Code that must survive a recompile should not depend on package variables for correctness. Store the data in a table or reread it from the source.
- A caller that can safely retry may catch ORA-04068 and repeat the call once.
- A stateless package, one with no package-level variables, does not raise this error when it is recompiled.
Resetting by hand
To free all package state in your own session, call DBMS_SESSION.RESET_PACKAGE.
BEGIN
DBMS_SESSION.RESET_PACKAGE;
END;
/
BEGIN
DBMS_OUTPUT.PUT_LINE(visit_log.visit_count);
END;
/The second block prints 0. The reset takes effect when the top-level call that made the request returns, not in the middle of the block. For that reason the example uses two separate blocks. If you called RESET_PACKAGE and then read visit_count in the same block, you would still see the old value.
This is useful in test suites, where you want each test to start from a known state.
Public variables are risky
A variable in the specification can be read and changed by any code that has EXECUTE on the package.
CREATE OR REPLACE PACKAGE app_settings AS
g_debug BOOLEAN := FALSE;
END app_settings;
/
BEGIN
app_settings.g_debug := TRUE;
END;
/This works, but it lets every caller modify the value with no validation, and you cannot later change how the value is stored without changing the specification. Changing the specification invalidates every dependent object.
A better design keeps the variable private and exposes a getter and setter.
CREATE OR REPLACE PACKAGE app_settings AS
PROCEDURE set_debug(p_on IN BOOLEAN);
FUNCTION is_debug RETURN BOOLEAN;
END app_settings;
/
CREATE OR REPLACE PACKAGE BODY app_settings AS
g_debug BOOLEAN := FALSE;
PROCEDURE set_debug(p_on IN BOOLEAN) IS
BEGIN
g_debug := NVL(p_on, FALSE);
END set_debug;
FUNCTION is_debug RETURN BOOLEAN IS
BEGIN
RETURN g_debug;
END is_debug;
END app_settings;
/Now the body controls every change. You can add validation, logging, or a different storage mechanism without touching the specification.
Connection pools and shared sessions
Many applications connect through a connection pool. The pool keeps database sessions open and lends them to different application users in turn. Package state belongs to the database session, not to the application user, so it stays in the session when the pool returns it.
The reverse problem also occurs. Two consecutive requests from one user may be served by different sessions. A value set by the first request is then missing in the second. Both problems have the same cause: the session, not the user, owns the state.
How much memory state uses
Package state takes memory in the session's own memory area (the UGA, which sits in the server process memory for a dedicated connection). The total is the per-session size multiplied by the number of sessions. A package that loads a 50 MB collection is harmless with one session and a problem with 2,000. When you cache large data in a package, size it for your session count, or keep the cache small and load it on demand.
State from open cursors is also kept. A package-level cursor that you open and never close stays open until the session ends. Close cursors when you finish with them, and remember that each open cursor counts against the OPEN_CURSORS limit.
A practical pattern: a lazy cache
A common safe use of state is a cache that is filled on demand and can always be rebuilt. If the state is lost, the next call simply refills it.
CREATE OR REPLACE PACKAGE dept_cache AS
FUNCTION dept_name(p_department_id IN departments.department_id%TYPE)
RETURN departments.department_name%TYPE;
PROCEDURE clear;
END dept_cache;
/
CREATE OR REPLACE PACKAGE BODY dept_cache AS
TYPE t_names IS TABLE OF departments.department_name%TYPE
INDEX BY PLS_INTEGER;
g_names t_names;
FUNCTION dept_name(p_department_id IN departments.department_id%TYPE)
RETURN departments.department_name%TYPE IS
BEGIN
IF NOT g_names.EXISTS(p_department_id) THEN
SELECT department_name
INTO g_names(p_department_id)
FROM departments
WHERE department_id = p_department_id;
END IF;
RETURN g_names(p_department_id);
END dept_name;
PROCEDURE clear IS
BEGIN
g_names.DELETE;
END clear;
END dept_cache;
/The first lookup for a department runs a query. Later lookups in the same session read from memory. If a department is renamed in another session, this session keeps returning the old name until it calls clear or ends. That is acceptable for reference data that rarely changes, and wrong for data that changes often.
Summary of rules
- Package-level variables and open cursors are state. Constants are not.
- Each session has its own copy, created on first reference.
- State survives
COMMIT,ROLLBACKand the end of the calling block. It does not survive the end of the session. - Recompiling a package body discards the state of every session that holds it, and each of those sessions gets ORA-04068 once.
- Keep variables private, expose getters and setters, and treat any cached data as possibly stale.
Exercise
A session calls visitlog.recordvisit('/a') twice, then runs ROLLBACK, and then calls visitlog.visitcount. What does visit_count return, and why?
Show answer
It returns 2. Package variables are session memory and are not part of the transaction, so ROLLBACK does not restore g_count. Only changes to table data are undone.
Exercise
Session A has been using a package that has a private variable. A developer recompiles the package body in session B. What happens the next time session A calls the package, and what happens if it repeats the call?
Show answer
The first call raises ORA-04068 (with ORA-04061 and ORA-06508), because the state held by session A was discarded and the call did not run. The repeated call succeeds, against a new copy of the state with all variables back at their initial values.
Exercise
Why is a public variable such as appsettings.gdebug a worse design than a private variable with setdebug and isdebug subprograms?
Show answer
Any caller can change a public variable with no validation, and changing how it is stored means changing the specification, which invalidates all dependent objects. With a private variable, the body controls every change and can be altered freely without affecting callers.