Skip to main content

rustjava_runtime/classes/java/util/
timer.rs

1use alloc::vec;
2
3use jvm::{ClassInstanceRef, Jvm, Result};
4use jvm_class_proto::{JavaFieldProto, JavaMethodProto};
5use jvm_types::{ClassAccessFlags, FieldAccessFlags, MethodAccessFlags};
6
7use crate::{
8    RuntimeClassProto, RuntimeContext,
9    classes::java::util::{Date, TimerTask, TimerTaskQueue, TimerThread},
10};
11
12// class java.util.Timer
13pub struct Timer;
14
15impl Timer {
16    pub fn as_proto() -> RuntimeClassProto {
17        RuntimeClassProto {
18            name: "java/util/Timer",
19            parent_class: Some("java/lang/Object"),
20            interfaces: vec![],
21            methods: vec![
22                JavaMethodProto::new("<init>", "()V", Self::init, MethodAccessFlags::PUBLIC),
23                JavaMethodProto::new("schedule", "(Ljava/util/TimerTask;J)V", Self::schedule_once, MethodAccessFlags::PUBLIC),
24                JavaMethodProto::new(
25                    "schedule",
26                    "(Ljava/util/TimerTask;Ljava/util/Date;)V",
27                    Self::schedule_date,
28                    MethodAccessFlags::PUBLIC,
29                ),
30                JavaMethodProto::new(
31                    "schedule",
32                    "(Ljava/util/TimerTask;JJ)V",
33                    Self::schedule_repeated,
34                    MethodAccessFlags::PUBLIC,
35                ),
36                JavaMethodProto::new(
37                    "schedule",
38                    "(Ljava/util/TimerTask;Ljava/util/Date;J)V",
39                    Self::schedule_date_repeated,
40                    MethodAccessFlags::PUBLIC,
41                ),
42                JavaMethodProto::new(
43                    "scheduleAtFixedRate",
44                    "(Ljava/util/TimerTask;JJ)V",
45                    Self::schedule_at_fixed_rate,
46                    MethodAccessFlags::PUBLIC,
47                ),
48                JavaMethodProto::new(
49                    "scheduleAtFixedRate",
50                    "(Ljava/util/TimerTask;Ljava/util/Date;J)V",
51                    Self::schedule_date_at_fixed_rate,
52                    MethodAccessFlags::PUBLIC,
53                ),
54                JavaMethodProto::new("cancel", "()V", Self::cancel, MethodAccessFlags::PUBLIC),
55            ],
56            fields: vec![JavaFieldProto::new(
57                "thread",
58                "Ljava/util/Timer$TimerThread;",
59                FieldAccessFlags::PRIVATE | FieldAccessFlags::FINAL,
60            )],
61            access_flags: ClassAccessFlags::PUBLIC,
62        }
63    }
64
65    async fn init(jvm: &Jvm, _: &mut RuntimeContext, mut this: ClassInstanceRef<Self>) -> Result<()> {
66        tracing::debug!("java.util.Timer::<init>({this:?})");
67
68        let _: () = jvm.invoke_special(&this, "java/lang/Object", "<init>", "()V", ()).await?;
69        let queue = jvm.new_class("java/util/Timer$TaskQueue", "()V", ()).await?;
70        let timer_thread = jvm
71            .new_class("java/util/Timer$TimerThread", "(Ljava/util/Timer$TaskQueue;)V", (queue,))
72            .await?;
73        jvm.put_field(
74            &mut this,
75            "java/util/Timer",
76            "thread",
77            "Ljava/util/Timer$TimerThread;",
78            timer_thread.clone(),
79        )
80        .await?;
81        let _: () = jvm
82            .invoke_virtual(&timer_thread, "java/util/Timer$TimerThread", "start", "()V", ())
83            .await?;
84        Ok(())
85    }
86
87    async fn schedule_once(
88        jvm: &Jvm,
89        context: &mut RuntimeContext,
90        this: ClassInstanceRef<Self>,
91        task: ClassInstanceRef<TimerTask>,
92        delay: i64,
93    ) -> Result<()> {
94        tracing::debug!("java.util.Timer::schedule({this:?}, {task:?}, {delay:?})");
95
96        if task.is_null() {
97            return Err(jvm.exception("java/lang/NullPointerException", "task").await);
98        }
99        if delay < 0 {
100            return Err(jvm.exception("java/lang/IllegalArgumentException", "negative delay").await);
101        }
102        let Some(time) = (context.now() as i64).checked_add(delay) else {
103            return Err(jvm.exception("java/lang/IllegalArgumentException", "illegal execution time").await);
104        };
105        if time < 0 {
106            return Err(jvm.exception("java/lang/IllegalArgumentException", "illegal execution time").await);
107        }
108        Self::sched(jvm, this, task, time, 0).await
109    }
110
111    async fn schedule_date(
112        jvm: &Jvm,
113        _: &mut RuntimeContext,
114        this: ClassInstanceRef<Self>,
115        task: ClassInstanceRef<TimerTask>,
116        date: ClassInstanceRef<Date>,
117    ) -> Result<()> {
118        tracing::debug!("java.util.Timer::schedule({this:?}, {task:?}, {date:?})");
119
120        if task.is_null() {
121            return Err(jvm.exception("java/lang/NullPointerException", "task").await);
122        }
123        if date.is_null() {
124            return Err(jvm.exception("java/lang/NullPointerException", "time").await);
125        }
126        let time: i64 = jvm.invoke_virtual(&date, "java/util/Date", "getTime", "()J", ()).await?;
127        if time < 0 {
128            return Err(jvm.exception("java/lang/IllegalArgumentException", "illegal execution time").await);
129        }
130        Self::sched(jvm, this, task, time, 0).await
131    }
132
133    async fn schedule_repeated(
134        jvm: &Jvm,
135        context: &mut RuntimeContext,
136        this: ClassInstanceRef<Self>,
137        task: ClassInstanceRef<TimerTask>,
138        delay: i64,
139        period: i64,
140    ) -> Result<()> {
141        tracing::debug!("java.util.Timer::schedule({this:?}, {task:?}, {delay:?}, {period:?})");
142
143        if task.is_null() {
144            return Err(jvm.exception("java/lang/NullPointerException", "task").await);
145        }
146        if delay < 0 {
147            return Err(jvm.exception("java/lang/IllegalArgumentException", "negative delay").await);
148        }
149        if period <= 0 {
150            return Err(jvm.exception("java/lang/IllegalArgumentException", "non-positive period").await);
151        }
152        let Some(time) = (context.now() as i64).checked_add(delay) else {
153            return Err(jvm.exception("java/lang/IllegalArgumentException", "illegal execution time").await);
154        };
155        if time < 0 {
156            return Err(jvm.exception("java/lang/IllegalArgumentException", "illegal execution time").await);
157        }
158        Self::sched(jvm, this, task, time, -period).await
159    }
160
161    async fn schedule_date_repeated(
162        jvm: &Jvm,
163        _: &mut RuntimeContext,
164        this: ClassInstanceRef<Self>,
165        task: ClassInstanceRef<TimerTask>,
166        date: ClassInstanceRef<Date>,
167        period: i64,
168    ) -> Result<()> {
169        tracing::debug!("java.util.Timer::schedule({this:?}, {task:?}, {date:?}, {period:?})");
170
171        if task.is_null() {
172            return Err(jvm.exception("java/lang/NullPointerException", "task").await);
173        }
174        if date.is_null() {
175            return Err(jvm.exception("java/lang/NullPointerException", "time").await);
176        }
177        if period <= 0 {
178            return Err(jvm.exception("java/lang/IllegalArgumentException", "non-positive period").await);
179        }
180        let time: i64 = jvm.invoke_virtual(&date, "java/util/Date", "getTime", "()J", ()).await?;
181        if time < 0 {
182            return Err(jvm.exception("java/lang/IllegalArgumentException", "illegal execution time").await);
183        }
184        Self::sched(jvm, this, task, time, -period).await
185    }
186
187    async fn schedule_at_fixed_rate(
188        jvm: &Jvm,
189        context: &mut RuntimeContext,
190        this: ClassInstanceRef<Self>,
191        task: ClassInstanceRef<TimerTask>,
192        delay: i64,
193        period: i64,
194    ) -> Result<()> {
195        tracing::debug!("java.util.Timer::scheduleAtFixedRate({this:?}, {task:?}, {delay:?}, {period:?})");
196
197        if task.is_null() {
198            return Err(jvm.exception("java/lang/NullPointerException", "task").await);
199        }
200        if delay < 0 {
201            return Err(jvm.exception("java/lang/IllegalArgumentException", "negative delay").await);
202        }
203        if period <= 0 {
204            return Err(jvm.exception("java/lang/IllegalArgumentException", "non-positive period").await);
205        }
206        let Some(time) = (context.now() as i64).checked_add(delay) else {
207            return Err(jvm.exception("java/lang/IllegalArgumentException", "illegal execution time").await);
208        };
209        if time < 0 {
210            return Err(jvm.exception("java/lang/IllegalArgumentException", "illegal execution time").await);
211        }
212        Self::sched(jvm, this, task, time, period).await
213    }
214
215    async fn schedule_date_at_fixed_rate(
216        jvm: &Jvm,
217        _: &mut RuntimeContext,
218        this: ClassInstanceRef<Self>,
219        task: ClassInstanceRef<TimerTask>,
220        date: ClassInstanceRef<Date>,
221        period: i64,
222    ) -> Result<()> {
223        tracing::debug!("java.util.Timer::scheduleAtFixedRate({this:?}, {task:?}, {date:?}, {period:?})");
224
225        if task.is_null() {
226            return Err(jvm.exception("java/lang/NullPointerException", "task").await);
227        }
228        if date.is_null() {
229            return Err(jvm.exception("java/lang/NullPointerException", "time").await);
230        }
231        if period <= 0 {
232            return Err(jvm.exception("java/lang/IllegalArgumentException", "non-positive period").await);
233        }
234        let time: i64 = jvm.invoke_virtual(&date, "java/util/Date", "getTime", "()J", ()).await?;
235        if time < 0 {
236            return Err(jvm.exception("java/lang/IllegalArgumentException", "illegal execution time").await);
237        }
238        Self::sched(jvm, this, task, time, period).await
239    }
240
241    async fn sched(jvm: &Jvm, this: ClassInstanceRef<Self>, mut task: ClassInstanceRef<TimerTask>, time: i64, period: i64) -> Result<()> {
242        let period = if !(-(i64::MAX >> 1)..=(i64::MAX >> 1)).contains(&period) {
243            period >> 1
244        } else {
245            period
246        };
247        if period != 0 {
248            let period_magnitude = if period < 0 {
249                let Some(period_magnitude) = period.checked_neg() else {
250                    return Err(jvm.exception("java/lang/IllegalArgumentException", "period overflow").await);
251                };
252                period_magnitude
253            } else {
254                period
255            };
256            if time.checked_add(period_magnitude).is_none() {
257                return Err(jvm.exception("java/lang/IllegalArgumentException", "period overflow").await);
258            }
259        }
260
261        let thread: ClassInstanceRef<TimerThread> = jvm.get_field(&this, "java/util/Timer", "thread", "Ljava/util/Timer$TimerThread;").await?;
262        let mut queue: ClassInstanceRef<TimerTaskQueue> = jvm
263            .get_field(&thread, "java/util/Timer$TimerThread", "queue", "Ljava/util/Timer$TaskQueue;")
264            .await?;
265        let lock: ClassInstanceRef<crate::classes::java::lang::Object> =
266            jvm.get_field(&task, "java/util/TimerTask", "lock", "Ljava/lang/Object;").await?;
267
268        jvm.monitor_enter(&queue).await?;
269        let schedule_result = async {
270            if !jvm
271                .get_field::<bool>(&thread, "java/util/Timer$TimerThread", "newTasksMayBeScheduled", "Z")
272                .await?
273            {
274                return Err(jvm.exception("java/lang/IllegalStateException", "timer already cancelled").await);
275            }
276
277            jvm.monitor_enter(&lock).await?;
278            let task_result = async {
279                if jvm.get_field::<i32>(&task, "java/util/TimerTask", "state", "I").await? != TimerTask::VIRGIN {
280                    return Err(jvm
281                        .exception("java/lang/IllegalStateException", "task already scheduled or cancelled")
282                        .await);
283                }
284                jvm.put_field(&mut task, "java/util/TimerTask", "nextExecutionTime", "J", time).await?;
285                jvm.put_field(&mut task, "java/util/TimerTask", "period", "J", period).await?;
286                jvm.put_field(&mut task, "java/util/TimerTask", "state", "I", TimerTask::SCHEDULED)
287                    .await?;
288                TimerTaskQueue::add(jvm, &mut queue, task.clone()).await
289            }
290            .await;
291            let task_exit_result = jvm.monitor_exit(&lock).await;
292            let new_first = match task_result {
293                Ok(new_first) => {
294                    task_exit_result?;
295                    new_first
296                }
297                Err(error) => {
298                    task_exit_result?;
299                    return Err(error);
300                }
301            };
302            if new_first {
303                jvm.object_notify(&queue, 1).await?;
304            }
305            Ok(())
306        }
307        .await;
308        let queue_exit_result = jvm.monitor_exit(&queue).await;
309        match schedule_result {
310            Ok(()) => queue_exit_result,
311            Err(error) => {
312                queue_exit_result?;
313                Err(error)
314            }
315        }
316    }
317
318    async fn cancel(jvm: &Jvm, _: &mut RuntimeContext, this: ClassInstanceRef<Self>) -> Result<()> {
319        tracing::debug!("java.util.Timer::cancel({this:?})");
320
321        let mut thread: ClassInstanceRef<TimerThread> = jvm.get_field(&this, "java/util/Timer", "thread", "Ljava/util/Timer$TimerThread;").await?;
322        let mut queue: ClassInstanceRef<TimerTaskQueue> = jvm
323            .get_field(&thread, "java/util/Timer$TimerThread", "queue", "Ljava/util/Timer$TaskQueue;")
324            .await?;
325        jvm.monitor_enter(&queue).await?;
326        let cancel_result = async {
327            jvm.put_field(&mut thread, "java/util/Timer$TimerThread", "newTasksMayBeScheduled", "Z", false)
328                .await?;
329            TimerTaskQueue::clear(jvm, &mut queue).await?;
330            jvm.object_notify(&queue, usize::MAX).await
331        }
332        .await;
333        let exit_result = jvm.monitor_exit(&queue).await;
334        match cancel_result {
335            Ok(()) => exit_result,
336            Err(error) => {
337                exit_result?;
338                Err(error)
339            }
340        }
341    }
342}