Sub topic 12
SERIALLY_REUSABLE packages
This chapter assumes you can write a package specification and body, and that you know a package variable normally keeps its value for the whole session. It covers PRAGMA SERIALLY_REUSABLE, which changes that lifetime from the session to a single database call. You will see how the pragma works, what it restricts, and when it is worth using.
The problem the pragma solves
Ordinary package state lives in the session's memory. In a dedicated-server connection, that memory is in the PGA. The memory stays allocated until the session ends or the package is reinstantiated. Each session that touches the package gets its own copy.
This is the behavior you want for a counter, a cache, or a session setting. It becomes a cost when a package holds a large collection, and thousands of sessions each call it once and then sit idle. Every one of them keeps its copy of that collection until it disconnects. This happens often with connection pools, where sessions are long-lived and mostly idle.
PRAGMA SERIALLY_REUSABLE changes the lifetime of the state:
- The package's state is kept in a work area in the SGA, not in each session's memory.
- The work area belongs to the package only while a server call is running. A server call is one round trip from the client, such as one anonymous block or one
CALLstatement. - When the call ends, the work area goes back to a pool and the state is discarded.
- The next call that references the package starts from a fresh state, and the initialization section runs again.
The memory needed therefore scales with the number of calls running at the same moment, not with the number of connected sessions.
Declaring a serially reusable package
Put PRAGMA SERIALLY_REUSABLE; in the declaration section of the specification and again in the body. Both are required. If only one of them has the pragma, compilation fails.
CREATE OR REPLACE PACKAGE sr_counter AS
PRAGMA SERIALLY_REUSABLE;
g_hits PLS_INTEGER := 0;
PROCEDURE hit;
END sr_counter;
/
CREATE OR REPLACE PACKAGE BODY sr_counter AS
PRAGMA SERIALLY_REUSABLE;
PROCEDURE hit IS
BEGIN
g_hits := g_hits + 1;
END hit;
END sr_counter;
/To see the difference, create a second package with the same logic and no pragma:
CREATE OR REPLACE PACKAGE plain_counter AS
g_hits PLS_INTEGER := 0;
PROCEDURE hit;
END plain_counter;
/
CREATE OR REPLACE PACKAGE BODY plain_counter AS
PROCEDURE hit IS
BEGIN
g_hits := g_hits + 1;
END hit;
END plain_counter;
/Seeing the lifetime difference
Run these blocks one after another in the same session. In SQL*Plus and SQLcl, each block is a separate server call. Turn on output first with SET SERVEROUTPUT ON.
BEGIN
sr_counter.hit;
sr_counter.hit;
plain_counter.hit;
plain_counter.hit;
DBMS_OUTPUT.PUT_LINE('sr = ' || sr_counter.g_hits);
DBMS_OUTPUT.PUT_LINE('plain = ' || plain_counter.g_hits);
END;
/
BEGIN
sr_counter.hit;
plain_counter.hit;
DBMS_OUTPUT.PUT_LINE('sr = ' || sr_counter.g_hits);
DBMS_OUTPUT.PUT_LINE('plain = ' || plain_counter.g_hits);
END;
/The first block prints sr = 2 and plain = 2. The second block prints sr = 1 and plain = 3. The ordinary package remembered its value across the two calls. The serially reusable package started over, because the first call ended and released its state.
Inside a single call, a serially reusable package behaves like any other package. All the hit calls within one block see the same variable. Only the boundary between calls matters.
What resets, and what runs again
Because the whole state is discarded at the end of a call, everything about the package's initialization is repeated for each call that uses it.
- Variable defaults. A declaration such as
g_hits PLS_INTEGER := 0;is evaluated again at the start of each call that references the package. - The initialization section. The
BEGIN ... ENDblock at the bottom of the body runs again for each such call, not once per session. If it does expensive work, such as querying a lookup table, that work now repeats on every call. - Cursors. A package-level cursor left open at the end of a call does not stay open for the next one. Do not design code that expects to fetch a few rows in one call and the rest in the next.
- Collections and records. Their contents are gone. Anything you want to keep must be written to a table, a context, or a non-serially-reusable package.
Restrictions
The pragma is not free. The state exists only while a call is in progress, so Oracle forbids access paths where it cannot guarantee that.
- Both parts need the pragma. A specification with the pragma and a body without it (or the reverse) does not compile.
- No access from SQL. You cannot read the package's state from a SQL statement. A function that reads a serially reusable package variable fails at run time with
ORA-06534if you call it from aSELECT. Calling the same function from PL/SQL is fine. - No access from triggers. Triggers cannot reference the package state either.
CREATE OR REPLACE FUNCTION current_hits RETURN PLS_INTEGER IS
BEGIN
RETURN sr_counter.g_hits;
END current_hits;
/
-- Fine: called from PL/SQL.
BEGIN
DBMS_OUTPUT.PUT_LINE(current_hits);
END;
/
-- Fails with ORA-06534: the function reads serially reusable state inside SQL.
SELECT current_hits FROM dual;Decision criteria
Use the pragma when all of these are true:
- The package holds a lot of memory, such as large collections or big
VARCHAR2buffers. - It is used briefly within one call and its content is rebuilt each time.
- Many sessions stay connected, so per-session memory is the scarce resource.
Do not use it when any of these is true:
- The package is a cache, a session setting, a counter, or a login flag. These need to survive between calls.
- The initialization section is expensive. It will run on each call.
- Some of the code that needs the data runs inside SQL statements or triggers.
For most packages, ordinary session state is the right default. The pragma trades a convenience (state that persists) for a memory saving, and you only get that saving when the package really is large and short-lived.
| Property | Ordinary package | SERIALLY_REUSABLE package |
|---|---|---|
| State lifetime | Session | One server call |
| Where state lives | Session memory (PGA in dedicated server) | Pooled work area in the SGA |
| Memory scales with | Number of sessions that used the package | Number of simultaneous calls |
| Initialization section runs | Once per session, on first reference | At the start of each call that references it |
| Usable from SQL and triggers | Yes | Package state cannot be accessed |
| Pragma location | None | Specification and body |
Common mistakes
- Expecting persistence. The most common error is converting a package to serially reusable and then finding that a counter or flag resets. The reset is the designed behavior.
- Testing in one block. If you test a serially reusable package inside a single anonymous block, it behaves normally and the pragma appears to do nothing. Test across separate calls.
- Adding the pragma to only one part. The compile error points at the mismatch between the specification and the body. Add the pragma to both.
- Using it for a cache. A lookup cache that is reloaded on every call is slower than a plain package that loads it once per session. The memory you save is paid for in CPU and I/O.
Exercise
A package has the pragma SERIALLYREUSABLE in both parts and holds a public variable gtotal initialized to 0. A client session runs one anonymous block that calls addtototal(5), and then runs a second block that calls addtototal(7) and prints g_total. What does the second block print, and what would it print if the pragma were removed from both parts?
Show answer
With the pragma, the second block prints 7, because the first call ended and released the state, so g_total started again at 0. Without the pragma, it prints 12, because the variable lasts for the whole session.
Exercise
You compile a specification with PRAGMA SERIALLY_REUSABLE but forget the pragma in the body. What happens, and what is the fix?
Show answer
Compilation fails, because the pragma must appear in both the specification and the body. Add PRAGMA SERIALLY_REUSABLE; to the declaration section of the body and recompile it.
Exercise
A team wants to cache a lookup table of country codes in a package so that a SQL query can call a function that reads the cache. Should they make the package SERIALLY_REUSABLE? Give two reasons.
Show answer
No. First, a cache must survive between calls, but serially reusable state is discarded at the end of each call, so the cache would be rebuilt each time. Second, the package state cannot be accessed from a SQL statement, so a function called from the query that reads that state would fail with ORA-06534.