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("cancel", "()V", Self::cancel, MethodAccessFlags::PUBLIC),
49            ],
50            fields: vec![JavaFieldProto::new(
51                "thread",
52                "Ljava/util/Timer$TimerThread;",
53                FieldAccessFlags::PRIVATE | FieldAccessFlags::FINAL,
54            )],
55            access_flags: ClassAccessFlags::PUBLIC,
56        }
57    }
58
59    async fn init(jvm: &Jvm, _: &mut RuntimeContext, mut this: ClassInstanceRef<Self>) -> Result<()> {
60        tracing::debug!("java.util.Timer::<init>({this:?})");
61
62        let _: () = jvm.invoke_special(&this, "java/lang/Object", "<init>", "()V", ()).await?;
63        let queue = jvm.new_class("java/util/Timer$TaskQueue", "()V", ()).await?;
64        let timer_thread = jvm
65            .new_class("java/util/Timer$TimerThread", "(Ljava/util/Timer$TaskQueue;)V", (queue,))
66            .await?;
67        jvm.put_field(&mut this, "thread", "Ljava/util/Timer$TimerThread;", timer_thread.clone())
68            .await?;
69        let _: () = jvm
70            .invoke_virtual(&timer_thread, "java/util/Timer$TimerThread", "start", "()V", ())
71            .await?;
72        Ok(())
73    }
74
75    async fn schedule_once(
76        jvm: &Jvm,
77        context: &mut RuntimeContext,
78        this: ClassInstanceRef<Self>,
79        task: ClassInstanceRef<TimerTask>,
80        delay: i64,
81    ) -> Result<()> {
82        tracing::debug!("java.util.Timer::schedule({this:?}, {task:?}, {delay:?})");
83
84        if task.is_null() {
85            return Err(jvm.exception("java/lang/NullPointerException", "task").await);
86        }
87        if delay < 0 {
88            return Err(jvm.exception("java/lang/IllegalArgumentException", "negative delay").await);
89        }
90        let Some(time) = (context.now() as i64).checked_add(delay) else {
91            return Err(jvm.exception("java/lang/IllegalArgumentException", "illegal execution time").await);
92        };
93        if time < 0 {
94            return Err(jvm.exception("java/lang/IllegalArgumentException", "illegal execution time").await);
95        }
96        Self::sched(jvm, this, task, time, 0).await
97    }
98
99    async fn schedule_date(
100        jvm: &Jvm,
101        _: &mut RuntimeContext,
102        this: ClassInstanceRef<Self>,
103        task: ClassInstanceRef<TimerTask>,
104        date: ClassInstanceRef<Date>,
105    ) -> Result<()> {
106        tracing::debug!("java.util.Timer::schedule({this:?}, {task:?}, {date:?})");
107
108        if task.is_null() {
109            return Err(jvm.exception("java/lang/NullPointerException", "task").await);
110        }
111        if date.is_null() {
112            return Err(jvm.exception("java/lang/NullPointerException", "time").await);
113        }
114        let time: i64 = jvm.invoke_virtual(&date, "java/util/Date", "getTime", "()J", ()).await?;
115        if time < 0 {
116            return Err(jvm.exception("java/lang/IllegalArgumentException", "illegal execution time").await);
117        }
118        Self::sched(jvm, this, task, time, 0).await
119    }
120
121    async fn schedule_repeated(
122        jvm: &Jvm,
123        context: &mut RuntimeContext,
124        this: ClassInstanceRef<Self>,
125        task: ClassInstanceRef<TimerTask>,
126        delay: i64,
127        period: i64,
128    ) -> Result<()> {
129        tracing::debug!("java.util.Timer::schedule({this:?}, {task:?}, {delay:?}, {period:?})");
130
131        if task.is_null() {
132            return Err(jvm.exception("java/lang/NullPointerException", "task").await);
133        }
134        if delay < 0 {
135            return Err(jvm.exception("java/lang/IllegalArgumentException", "negative delay").await);
136        }
137        if period <= 0 {
138            return Err(jvm.exception("java/lang/IllegalArgumentException", "non-positive period").await);
139        }
140        let Some(time) = (context.now() as i64).checked_add(delay) else {
141            return Err(jvm.exception("java/lang/IllegalArgumentException", "illegal execution time").await);
142        };
143        if time < 0 {
144            return Err(jvm.exception("java/lang/IllegalArgumentException", "illegal execution time").await);
145        }
146        Self::sched(jvm, this, task, time, -period).await
147    }
148
149    async fn schedule_date_repeated(
150        jvm: &Jvm,
151        _: &mut RuntimeContext,
152        this: ClassInstanceRef<Self>,
153        task: ClassInstanceRef<TimerTask>,
154        date: ClassInstanceRef<Date>,
155        period: i64,
156    ) -> Result<()> {
157        tracing::debug!("java.util.Timer::schedule({this:?}, {task:?}, {date:?}, {period:?})");
158
159        if task.is_null() {
160            return Err(jvm.exception("java/lang/NullPointerException", "task").await);
161        }
162        if date.is_null() {
163            return Err(jvm.exception("java/lang/NullPointerException", "time").await);
164        }
165        if period <= 0 {
166            return Err(jvm.exception("java/lang/IllegalArgumentException", "non-positive period").await);
167        }
168        let time: i64 = jvm.invoke_virtual(&date, "java/util/Date", "getTime", "()J", ()).await?;
169        if time < 0 {
170            return Err(jvm.exception("java/lang/IllegalArgumentException", "illegal execution time").await);
171        }
172        Self::sched(jvm, this, task, time, -period).await
173    }
174
175    async fn schedule_at_fixed_rate(
176        jvm: &Jvm,
177        context: &mut RuntimeContext,
178        this: ClassInstanceRef<Self>,
179        task: ClassInstanceRef<TimerTask>,
180        delay: i64,
181        period: i64,
182    ) -> Result<()> {
183        tracing::debug!("java.util.Timer::scheduleAtFixedRate({this:?}, {task:?}, {delay:?}, {period:?})");
184
185        if task.is_null() {
186            return Err(jvm.exception("java/lang/NullPointerException", "task").await);
187        }
188        if delay < 0 {
189            return Err(jvm.exception("java/lang/IllegalArgumentException", "negative delay").await);
190        }
191        if period <= 0 {
192            return Err(jvm.exception("java/lang/IllegalArgumentException", "non-positive period").await);
193        }
194        let Some(time) = (context.now() as i64).checked_add(delay) else {
195            return Err(jvm.exception("java/lang/IllegalArgumentException", "illegal execution time").await);
196        };
197        if time < 0 {
198            return Err(jvm.exception("java/lang/IllegalArgumentException", "illegal execution time").await);
199        }
200        Self::sched(jvm, this, task, time, period).await
201    }
202
203    async fn sched(jvm: &Jvm, this: ClassInstanceRef<Self>, mut task: ClassInstanceRef<TimerTask>, time: i64, period: i64) -> Result<()> {
204        let period = if !(-(i64::MAX >> 1)..=(i64::MAX >> 1)).contains(&period) {
205            period >> 1
206        } else {
207            period
208        };
209        if period != 0 {
210            let period_magnitude = if period < 0 {
211                let Some(period_magnitude) = period.checked_neg() else {
212                    return Err(jvm.exception("java/lang/IllegalArgumentException", "period overflow").await);
213                };
214                period_magnitude
215            } else {
216                period
217            };
218            if time.checked_add(period_magnitude).is_none() {
219                return Err(jvm.exception("java/lang/IllegalArgumentException", "period overflow").await);
220            }
221        }
222
223        let thread: ClassInstanceRef<TimerThread> = jvm.get_field(&this, "thread", "Ljava/util/Timer$TimerThread;").await?;
224        let mut queue: ClassInstanceRef<TimerTaskQueue> = jvm.get_field(&thread, "queue", "Ljava/util/Timer$TaskQueue;").await?;
225        let lock: ClassInstanceRef<crate::classes::java::lang::Object> = jvm.get_field(&task, "lock", "Ljava/lang/Object;").await?;
226
227        jvm.monitor_enter(&queue).await?;
228        let schedule_result = async {
229            if !jvm.get_field::<bool>(&thread, "newTasksMayBeScheduled", "Z").await? {
230                return Err(jvm.exception("java/lang/IllegalStateException", "timer already cancelled").await);
231            }
232
233            jvm.monitor_enter(&lock).await?;
234            let task_result = async {
235                if jvm.get_field::<i32>(&task, "state", "I").await? != TimerTask::VIRGIN {
236                    return Err(jvm
237                        .exception("java/lang/IllegalStateException", "task already scheduled or cancelled")
238                        .await);
239                }
240                jvm.put_field(&mut task, "nextExecutionTime", "J", time).await?;
241                jvm.put_field(&mut task, "period", "J", period).await?;
242                jvm.put_field(&mut task, "state", "I", TimerTask::SCHEDULED).await?;
243                TimerTaskQueue::add(jvm, &mut queue, task.clone()).await
244            }
245            .await;
246            let task_exit_result = jvm.monitor_exit(&lock).await;
247            let new_first = match task_result {
248                Ok(new_first) => {
249                    task_exit_result?;
250                    new_first
251                }
252                Err(error) => {
253                    task_exit_result?;
254                    return Err(error);
255                }
256            };
257            if new_first {
258                jvm.object_notify(&queue, 1).await?;
259            }
260            Ok(())
261        }
262        .await;
263        let queue_exit_result = jvm.monitor_exit(&queue).await;
264        match schedule_result {
265            Ok(()) => queue_exit_result,
266            Err(error) => {
267                queue_exit_result?;
268                Err(error)
269            }
270        }
271    }
272
273    async fn cancel(jvm: &Jvm, _: &mut RuntimeContext, this: ClassInstanceRef<Self>) -> Result<()> {
274        tracing::debug!("java.util.Timer::cancel({this:?})");
275
276        let mut thread: ClassInstanceRef<TimerThread> = jvm.get_field(&this, "thread", "Ljava/util/Timer$TimerThread;").await?;
277        let mut queue: ClassInstanceRef<TimerTaskQueue> = jvm.get_field(&thread, "queue", "Ljava/util/Timer$TaskQueue;").await?;
278        jvm.monitor_enter(&queue).await?;
279        let cancel_result = async {
280            jvm.put_field(&mut thread, "newTasksMayBeScheduled", "Z", false).await?;
281            TimerTaskQueue::clear(jvm, &mut queue).await?;
282            jvm.object_notify(&queue, usize::MAX).await
283        }
284        .await;
285        let exit_result = jvm.monitor_exit(&queue).await;
286        match cancel_result {
287            Ok(()) => exit_result,
288            Err(error) => {
289                exit_result?;
290                Err(error)
291            }
292        }
293    }
294}