2

I would like to write some JSON every 5th second. I'm using Jackson to write the JSON, but it seem to block my TimerTask. If I don't write JSON, the TimerTask is run every 5th second, but when I try to write JSON it's blocked and only run once. How can I fix this?

public class MyTimerTask extends TimerTask {

    public static void main(String[] args) {

        Timer timer = new Timer();

        // execute MyTimerTask every 5th second
        timer.scheduleAtFixedRate(new MyTimerTask(), 1000L, 5 * 1000L);
    }

    @Override
    public void run() {
        System.out.println("timertask");

        // Write JSON to System.out
        ObjectMapper mapper = new ObjectMapper();
        try {
            mapper.writeValue(System.out, "Hello");
        } catch (Exception e1) {
            e1.printStackTrace();
        }
    }
}

Here is my stack dump for the Timer thread:

"Timer-0" prio=6 tid=0x02488000 nid=0x10ec in Object.wait() [0x04a6f000]
   java.lang.Thread.State: TIMED_WAITING (on object monitor)
        at java.lang.Object.wait(Native Method)
        - waiting on <0x24577fa8> (a java.util.TaskQueue)
        at java.util.TimerThread.mainLoop(Unknown Source)
        - locked <0x24577fa8> (a java.util.TaskQueue)
        at java.util.TimerThread.run(Unknown Source)
Jonas
  • 121,568
  • 97
  • 310
  • 388

2 Answers2

1

The problem is with your use of System.out, not with Jackson.

StaxMan
  • 113,358
  • 34
  • 211
  • 239
0

is it blocked, or is it just throwing an exception which you aren't catching, which effectively cancels your task?

as a side not "printStackTrace()" is almost never a useful form of exception handling. either don't catch the exception or log it meaningfully. just calling "printStackTrace()" is asking to hide bugs.

if your task really is blocked, then the next step is to get a stack dump of your hung program. this should show you what is causing the code to block.

jtahlborn
  • 52,909
  • 5
  • 76
  • 118
  • I updated my code using `Exception` instead to catch them all. – Jonas May 01 '11 at 21:16
  • updated my answer to indicate the next step, getting a stack dump. – jtahlborn May 01 '11 at 22:26
  • I added a "stack dump" but I don't really understand it. I hope it helps anyway. – Jonas May 01 '11 at 23:06
  • the "Timer-0" thread is the worker thread for the Timer. it is currently waiting before the next execution of the task. so, according to that stack dump, your timer is not blocked, but seems to be working just fine. maybe you didn't wait long enough? – jtahlborn May 02 '11 at 02:59
  • attach a debugger and step through the task execution. – jtahlborn May 02 '11 at 11:43