Backend Development 6 min read

Understanding Java Object Serialization and the transient Keyword

Java object serialization converts objects into byte streams for storage or transmission, while the transient keyword excludes specific fields from this process; this article explains serialization concepts, appropriate use cases for transient, provides code examples, and shows the impact on object state after deserialization.

Architect's Tech Stack
Architect's Tech Stack
Architect's Tech Stack
Understanding Java Object Serialization and the transient Keyword

In Java, object serialization means converting an object into a sequence of bytes that contain the object's data and metadata, allowing it to be written to a file, database, or transmitted over a network; deserialization restores the original object from those bytes.

The transient keyword marks fields that should not be serialized, which is useful when a field can be derived from other data, is irrelevant for persistence, or would unnecessarily increase storage size.

Typical scenarios for using transient include derived values such as a rectangle's area (which can be recomputed from width and height) and fields that are only needed at runtime, like counters used to detect modifications.

Example of a transient field in java.util.HashMap :

/**
 * The number of times this HashMap has been structurally modified
 * Structural modifications are those that change the number of mappings in
 * the HashMap or otherwise modify its internal structure (e.g., rehash).
 * This field is used to make iterators on Collection‑views of the HashMap
 * fail‑fast. (See ConcurrentModificationException).
 */
transient int modCount;

A more complete example shows a Spring component that processes a RabbitMQ message and uses a DAO to delete records; the class includes annotations, a logger, and a method that builds a parameter map before invoking the DAO:

package com.ecej.esmart.workform.queue;

import com.ecej.esmart.core.annotation.Log;
import com.ecej.esmart.workform.dao.EsmartBaseDao;
import com.ecej.nove.utils.common.BaseUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * 删除周期订单虚拟档期表
 */
@Component
@RabbitListener(queues = "${esmart.del.cycle.order.schedule}")
public class ReceiverDelCycleOrderSchedule {
    private static final Logger LOGGER = LoggerFactory.getLogger(ReceiverDelCycleOrderSchedule.class);

    @Resource
    private EsmartBaseDao esmartBaseDao;

    @Log("删除周期订单虚拟档期表")
    @RabbitHandler
    public void delCycleOrderSchedule(String parentOrderNo) {
        try {
            LOGGER.info("监听到的消息:{}", parentOrderNo);
            if (StringUtils.isNotEmpty(parentOrderNo)) {
                Map
objectMap = new HashMap<>();
                objectMap.put("parentOrderNo", parentOrderNo);
                esmartBaseDao.delete(
                    BaseUtils.makeClazzPath(com.ecej.esmart.workform.ecejservice.po.WorkOrderPo.class),
                    "delCycleOrderSchedule",
                    objectMap);
            }
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
    }
}

The demonstration prints three states: the original object (width = 3, height = 4, area = 12), the deserialized object where the transient area field is null, and the restored object after recomputing the area, confirming that using transient saves storage while still allowing reconstruction of the original state.

Reference: Why does Java have transient fields?

JavaSerializationtransientJava BasicsObject Serialization
Architect's Tech Stack
Written by

Architect's Tech Stack

Java backend, microservices, distributed systems, containerized programming, and more.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.