(Scala) Delay Run

I wrote a threading primitive and I’m very pleased with it. I plan to wrap all of my “save file” things in this, from now on.

Delay Run

This class acts as a sort of “once inactive for X do Y” pattern. In my design, I’m wrapping my save actions in it and triggering schedule() after practically every edit.

The class is passed a delay: Long value to specify how long to actually wait - I’m using 1.9831 seconds because it amuses me. If, during this delay, I tell it to “save” again; then the save is further delayed. When I really-really want the save to happen - there’s the joinwait() method which should work, but, it is kind of irrelevant for the time being. The full source is below for the interested.

/*
Peter LaValle / gmail com
2017-11-09

This is free and unencumbered software released into the public domain.

Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.

In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

For more information, please refer to <http://unlicense.org/>
*/
package peterlavalle

/**
    * creates a "thing" which can be "scheduled" to run after a delay.
    * if it is "scheduled" while waiting for the delay to expire, it will extend the delay.
    *
    * @param delay how long to wait
    * @return a runnable that can be run again and again
    */
abstract class DelayedRun(delay: Long) {
    private val pivotLock: Object = this
    private var nextEvent: Long = 0
    private var thread: Thread = null

    /**
        * do something
        */
    def action(): Unit

    def schedule(): Unit = {

        pivotLock.synchronized {

            // put the delay forward
            nextEvent = Math.max(nextEvent, System.currentTimeMillis() + delay)

            def self: DelayedRun = this

            // schedule a thread
            if (null == thread)
                thread = new Thread(s"DelayedRun(${System.identityHashCode(self)}) @ $action") {

                    override def run(): Unit = {

                        def wait: Long =
                            pivotLock synchronized {
                                nextEvent - System.currentTimeMillis()
                            }

                        while (0 < wait) {
                            // just wait a bunch
                            Thread.sleep(delay)
                        }

                        pivotLock synchronized {
                            if (null != thread) {
                                thread = null
                                action()
                            }
                        }
                    }

                    start()
                }
        }
    }

    def joinWait(): Unit = {

        def waitMore: Thread =
            pivotLock synchronized {
                thread
            }

        while (null != waitMore)
            waitMore.join(delay)

    }
}

  1. I’ll probably switch to 0.314 for documents, at the moment all my IDE has is a config file. [return]
Peter LaValle avatar
About Peter LaValle
honks at geese. speaks the byzantine languages that make the magic boxes do the things.
comments powered by Disqus