I'm trying to figure out a way to exit a method call if it takes more then say 2 seconds to execute everything in its method's body. For example, I have a huge list of strings and want to iterate through the list but only iterate as much of the strings as I can in 2 seconds. Say I have 9,000 objects in the list but can only iterate through 6,500 in 2 seconds, the method should stop after 2 second. Is this even possible to accomplish? I searched and found how to stop a thread and timers (how to start a method after a certain duration) but nothing on how to exit a method after a duration.
public ArrayList<String> removeWords(){
//Want some sort of timer here that stops method body after 2 seconds
for(String current: words){
words.remove(current);
}
}
public static void main(String [] args){
ArrayList<String> wordList = removeWords();
System.out.println("Number of words in list "+ wordList.size());
}