카테고리 없음

clone, finalize, wait, notify

오개발 2024. 10. 25. 14:03

1. clone

clone() 메소드는 객체를 복제할 때 사용됩니다. 

 

class Person implements Cloneable {
    String name;
    
    Person(String name) {
        this.name = name;
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}

public class CloneExample {
    public static void main(String[] args) {
        try {
            Person p1 = new Person("Alice");
            Person p2 = (Person) p1.clone();
            
            System.out.println(p1.name); // 출력: Alice
            System.out.println(p2.name); // 출력: Alice
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
    }
}

 

하지만 실무에서 사용해본적도 없고 사용할 일이 없다. 그리고 위험하다.

객체를 복사해서 비교 해보면 객체의 주소는 다르지만 그 안에 참조하는 필드 객체의 주소는 같다 영향을 받을수 있다.

 

 

2. finalize()

finalize() 메서드는 객체가 가비지 컬렉션될 때 호출됩니다. 주로 자원을 정리하는 데 사용될 수 있지만, 자바 9부터는 finalize()의 사용이 권장되지 않습니다.

 

권장 하지 않는 이유는 많은 이유가 있겠지만 개발자가 강제적으로 GC를 제거 한다면 복잡한 로직과 성능 저하가 나올듯합니다.

 

 

3. wait() , notify()

 

스레드관련해서 사용되는 메서드 입니다.

 

wait()는 스레드를 일시 정지시킬 때 사용됩니다

notify()는 대기 중인 스레드 중 하나를 깨워 실행을 재개할 수 있게 해줍니다

 

class SharedResource {
    synchronized void waitForNotification() {
        try {
            System.out.println("Waiting...");
            wait();  // 다른 스레드가 notify()를 호출할 때까지 기다림
            System.out.println("Notified!");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    
    synchronized void sendNotification() {
        System.out.println("Sending notification...");
        notify();  // 대기 중인 스레드를 깨움
    }
}

public class WaitNotifyExample {
    public static void main(String[] args) {
        SharedResource resource = new SharedResource();
        
        // 기다리는 스레드
        new Thread(() -> resource.waitForNotification()).start();
        
        // 알림을 보내는 스레드
        new Thread(() -> {
            try {
                Thread.sleep(2000);  // 2초 후 알림 전송
                resource.sendNotification();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
    }
}