KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
I'm using Timer and TimerTask to long poll for new messages for a chat application. I would like to examine two "slightly" different possibilities: 1 : Timer declared as local variable public List<MessageBean> getLastMessages(...) { [...] Timer timer = new Timer(true); //**Timer declared as local variable** while (someCondiction) { MessagesTimerTask returnMessagesTask = new MessagesTimerTask([...]); timer.schedule(returnMessagesTask, 6000); synchronized (listMessageBean) { listMessageBean.wait(); //notify is called in the MessagesTimerTask which extends TimerTask } } } * Problem: Every time i call the method, i can see that a new thread is created, [Timer-1], [Timer-2], etc.. And in Eclipse Debug window they all seem to be running even after the getLastMessages(..) finishes running and returns a value to the client. This may cause a huge problem if the timers are actually using threads, and after few transactions the server will eventually consume all the machine resources. 2 : Timer declared as local field private final Timer timer = new Timer(true); //**Timer declared as local field** public List<MessageBean> getLastMessages(...) { [...] while (someCondiction) { MessagesTimerTask returnMessagesTask = new MessagesTimerTask([...]); timer.schedule(returnMessagesTask, 6000); synchronized (listMessageBean) { listMessageBean.wait(); //notify is called in the MessagesTimerTask which extends TimerTask } } } * Problem: every time i call the method, the same thread is used [Thread-1], but i'm not sure if i make two consecutive calls, the latter will cancel/override the former (the class is @Autowired by spring) ? Any suggestions ? Thank you.
Tags (comma-separated)
Save Edits
Cancel