'멤버변수 공유@'에 해당되는 글 1

  1. 2009.03.23 멤버변수 문제점

멤버변수 문제점

public class NoticeCommand implements Command {
	
	private String next;
	
	public NoticeCommand (String next){
		this.next = next;
	}

	public String execute( String msg ) {
		...
		try {
			...
			if("UnavailableException".equals(msg)){
				...
				throw new UnavailableException();
			}else if("".equals(msg)){
				...
			}else{

			}
		} catch (UnavailableException e) { 
			logging ...
			next = "/";
		} catch (Exception e) {
			next = "/error.jsp";
		}
		return next;
	}
}
public class Main{

	private static final Map<String, Command> commands = new HashMap<String, Command>();
	static{
		commands.put("list", new NoticeCommand("/list.jsp"));
		...
	}
	
	private static Command lookupCommand(String cmd){
		...
		return command;
	}
	
	public static void main(String[] args) {
		
		Command command = lookupCommand("list");
		String result = command.execute("UnavailableException");
		System.out.println(result);

		result = command.execute("");
		System.out.println(result);
	}
}
대충 이런 코드인데,
UnavailableException 이 발생한 뒤부터 예외가 발생하지 않아도 result 는 / 이다.
로거를 찍어봐도 예외는 발생하지 않는데 result 는 / 다.

문제는 next 변수를 잘못 사용했기 때문에 발생했다.
NoticeCommand 는 한번 생성한 뒤 계속 재사용되므로 next 변수를 변경하지 말던가 로컬변수로 돌린다.
웹 환경의 다중 스레드에 의해서 접근되는 경우 더욱 조심해야 한다.