[java] 스택을 이용한 메모리 관리 시뮬레이션 구현하기

개요

이번 프로젝트는 자바의 스택을 이용하여 메모리 관리 시뮬레이션을 구현하는 것이다. 스택은 후입선출(LIFO) 구조의 자료구조로, 메모리 할당과 해제를 효율적으로 모델링하기에 적합하다.

구현 내용

  1. Stack 클래스 구현
    • 자바에서 제공하는 Stack 클래스를 활용하여 스택을 구현한다.
    • 일반적인 스택의 push와 pop 메서드를 구현하여 메모리의 할당과 해제를 흉내낸다.
    • 스택의 크기는 사용자가 설정할 수 있도록 한다.
  2. 메모리 관리 시뮬레이션 클래스 구현
    • 메모리 관리 시뮬레이션을 위한 클래스를 구현한다.
    • 스택 인스턴스를 생성하여 메모리 용량을 설정하고, 할당된 메모리 공간을 관리한다.
    • 사용자로부터 메모리 할당 및 해제 요청을 받아 스택에 적용한다.

예시 코드

import java.util.Stack;

public class MemorySimulation {
    private Stack<Integer> memoryStack;
    private int capacity;

    public MemorySimulation(int capacity) {
        this.memoryStack = new Stack<>();
        this.capacity = capacity;
    }

    public boolean allocateMemory(int size) {
        if (memoryStack.size() + size <= capacity) {
            for (int i = 0; i < size; i++) {
                memoryStack.push(i);
            }
            return true;
        } else {
            return false;
        }
    }

    public void deallocateMemory(int size) {
        for (int i = 0; i < size; i++) {
            memoryStack.pop();
        }
    }

    public static void main(String[] args) {
        MemorySimulation memorySimulation = new MemorySimulation(10);

        boolean allocated = memorySimulation.allocateMemory(5);
        System.out.println("Memory allocated: " + allocated);
        System.out.println("Current memory usage: " + memorySimulation.memoryStack.size());

        memorySimulation.deallocateMemory(3);
        System.out.println("Memory deallocated.");
        System.out.println("Current memory usage: " + memorySimulation.memoryStack.size());
    }
}

실행 결과

Memory allocated: true
Current memory usage: 5
Memory deallocated.
Current memory usage: 2

참고 자료