Are Thread.stop and friends ever safe in Java?

前端 未结 8 1141
清酒与你
清酒与你 2020-11-28 08:05

The stop(), suspend(), and resume() in java.lang.Thread are deprecated because they are unsafe. The Oracle recommended w

8条回答
  •  鱼传尺愫
    2020-11-28 08:27

    A concrete example would probably help here. If anyone can suggest a good alternative to the following use of stop I'd be very interested. Re-writing java.util.regex to support interruption doesn't count.

    import java.util.regex.*;
    import java.util.*;
    
    public class RegexInterruptTest {
    
        private static class BadRegexException extends RuntimeException { }
            final Thread mainThread = Thread.currentThread();
            TimerTask interruptTask = new TimerTask() {
                public void run() {
                    System.out.println("Stopping thread.");
                    // Doesn't work:
                    // mainThread.interrupt();
                    // Does work but is deprecated and nasty
                    mainThread.stop(new BadRegexException());
                }
            };
    
            Timer interruptTimer = new Timer(true);
            interruptTimer.schedule(interruptTask, 2000L);
    
            String s = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab";
            String exp = "(a+a+){1,100}";
            Pattern p = Pattern.compile(exp);
            Matcher m = p.matcher(s);
            try {
                System.out.println("Match: " + m.matches());
                interruptTimer.cancel();
            } catch(BadRegexException bre) {
                System.out.println("Oooops");
            } finally {
                System.out.println("All over");
            }
        }
    }
    

提交回复
热议问题