Extremely Serious

Month: January 2018

Singleton with Variable State

Looking at the following SingletonUtil class we know we can call generateXML method safely.

Code 1: SingletonUtil class for Studio Terminal

static class SingletonUtil {
  var _sbString : StringBuilder
  
  private static var _SELF : SingletonUtil as Instance = new SingletonUtil()

  private construct() {
    _sbString = new StringBuilder()
  }
  
  function generateXML(text : String) : String {
    _sbString.append("")
    _sbString.append(text?:"")
    _sbString.append("")
    var output = _sbString.toString()
    using(_sbString as IMonitorLock) {
      _sbString.delete(0, _sbString.length())
    }
    return output
  }
}

If we generate the XML like the following:

Code 2: GenerateXML via single thread.

print(SingletonUtil.Instance.generateXML("test"))
print(SingletonUtil.Instance.generateXML("test"))
print(SingletonUtil.Instance.generateXML("test"))

The output will be as expected and we can say it is safe:

Output 1

<text>test</text>
<text>test</text>
<text>test</text>

We are complacent that everything is working good since we can run it and can generate the expected Output 1. But don’t forget we are running it in a single thread. Thus we can say that this code is safe for single thread.

Lets try the same but this time with 10 threads and we are expecting the output to be like this:

Output 2

<text>test</text>
<text>test</text>
<text>test</text>
<text>test</text>
<text>test</text>
<text>test</text>
<text>test</text>
<text>test</text>
<text>test</text>
<text>test</text>

Run the following code in terminal:

Code 3: GenerateXML via multithread.

for (var idx in (1..10)) {
  var thread = new Thread(new Runnable() {
    override function run() {
      print(SingletonUtil.Instance.generateXML("test"))
    }
  })
  thread.start()
}

We will have a hard time generating our expected output this time. And we can say that this not thread-safe. There are three things we can do about this.

1.) If we don't have the source code, we can use locking on the client code. Let's use IMonitorLock for the simplicity and run it in studio terminal. The updated client code can be like the following and can generate Output 2:

Code 4: GenerateXML via multithread with locking.

for (var idx in (1..10)) {
  var thread = new Thread(new Runnable() {
    override function run() {
      var inst = SingletonUtil.Instance
      using(inst as IMonitorLock) {
        print(inst.generateXML("test"))
      }
    }
  })
  thread.start()
}

2.) If we have the source code and can update it, we can make the whole generate XML method to be synchronized like the following and use Code 3 to generate Output 2:

Code 5: SingletonUtil class for Studio Terminal with the whole generateXML is locking.

static class SingletonUtil {
  var _sbString : StringBuilder
  
  private static var _SELF : SingletonUtil as Instance = new SingletonUtil()

  private construct() {
    _sbString = new StringBuilder()
  }
  
  function generateXML(text : String) : String {
    using(_sbString as IMonitorLock) {
      _sbString.append("")
      _sbString.append(text?:"")
      _sbString.append("")
      var output = _sbString.toString()
      _sbString.delete(0, _sbString.length())
      return output
    }
  }
}

3.) If we have the source code and can update it, try to remove the variable state like the following and use Code 3 to generate Output 2:

Code 6: SingletonUtil class for Studio Terminal without shared state.

static class SingletonUtil {
  private static var _SELF : SingletonUtil as Instance = new SingletonUtil()

  private construct() {
  }
  
  function generateXML(text : String) : String {
    var _sbString = new StringBuilder() 
    _sbString.append("")
    _sbString.append(text?:"")
    _sbString.append("")
    var output = _sbString.toString()
    return output
  }
}

Refactoring difficult class to test to testable in Gosu

Use case

Normally if we like to create a utility class we normally implement it with static methods.

Problem

This is good if we can write unit tests on it. But most of the time this is not the case since it is difficult to write a unit on it. Specially, if the utility class that have a lots of static methods inside that depends on each other. For example, the following piece of code (i.e. Code 1) even though small authoring a test could be difficult.

Code 1. Small class that cannot be tested easily.

package example

uses java.lang.Math

class SampleCodeWithStaticMethods {

private construct() {}

static function myMethod() {
 var value = someAction() + 10
 print(value)
 }

static function someAction() : int {
 return (Math.round(Math.random()*100) as int) + 100
 }

}

Imagine write a unit test for myMethod. It is almost impossible because the method depends on someAction which is also a static method that returns random integer.

We need to refactor this to make it testable. The first thing we can do is identify if there are other static methods being called that are not a member of the class and make a separate non-static method for them. From code 1, those static method calls are:

- Print
- Math.round
- Math.random

Call those new member instance methods in place of the static method call. Making them contained in a separate method allows us to bypass them by overriding on a child class (i.e. basic OOP principle).

The next thing is remove all the static modifiers to convert all of them to member instance methods.

The refactored code would be like the following code.

Code 2. Refactored to use non-static methods

package example
uses java.lang.Math

class SampleCodeWithoutStaticMethods {

//Contains the call the to static print method.
 function output(value : int) {
 print(value)
 }

//Contains the call the Math.round and Math.random.
 function random() : int {
 return (Math.round(Math.random()*100) as int)
 }

function myMethod() {
 var value = someAction() + 10
 //Calls the member method that contains the static print method.
 output(value)
 }

function someAction() : int {
 return random() //Calls the member method that contains the static Math.round and Math.random method.
 + 100
 }

}

Now testing myMethod becomes so trivial (i.e. Code 3) using the very old behaviour of OOP (i.e. being polymorphic). The key is the inner class SampleCodeWithoutStaticMethodsMyMethod where we overrode someAction and output instance methods.

The someAction method now just return 25 which makes it more consistent than its original random behaviour.

The output method is just collecting what's being passed to it to result field instead of printing it.

Code 3. Unit test for myMethod

package example

uses gw.api.system.server.Runlevel
 uses gw.testharness.RunLevel

@gw.testharness.ServerTest
 @RunLevel(Runlevel.NONE)
 class SampleCodeWithoutStaticMethodsTest extends gw.testharness.TestBase {

class SampleCodeWithoutStaticMethodsMyMethod extends SampleCodeWithoutStaticMethods {
 var result : int

override function someAction() : int {
 return 25
 }

override function output(value : int) {
 result = value
 }
 }

function testMyMethod() {
 var testObj = new SampleCodeWithoutStaticMethodsMyMethod()
 testObj.myMethod()
 assertEquals(35, testObj.result)
 }

}

Registering Cygwin – NGINX as a Windows Service

The following procedure must be ran on an elevated cygwin terminal.

1. Run the following command and accept the defaults.

cygserver-config

2. Register the nginx as a service with the following command:

cygrunsrv --install nginx --path /usr/sbin/nginx.exe --disp "CYGWIN nginx" --termsig QUIT --shutdown --dep cygserver