WeakAssQueue

LIFO queue that will drop old elements when needed.

The Idea

Have a Last-In-First-Out queue (implements java.util.Queue<E>) that will release old elements so that garbage collection (GC) can remove them. Like a cache that is a stack.

Example: Undo Queue

A simple desktop app could have a queue of actions, so that the user can undo the last steps. In the settings the user can set how many actions can be undone. Lets say the users wants to be able to undo 20 actions. But that doesn’t mean we have to remove older actions as soon as the user has done more than 20. We can keep them in the queue, but use SoftReference. So GC can just remove them when the memory is actually full. But the queue makes sure the 20 newest actions are always protected from GC.

You can change the limit of the queue at any time.

Example: In Memory Log

Imagine you need a log with messages that get less relevant the older they are. The application keeps adding new messages all the time and you want to keep as many as possible. Insertion order is obviously important and usually you only want to iterate the lastest messages. Sometimes you want to dump them all into a text file.

So you can create a WeakAssQueue which will use a limit for the elements that are not protected. Whenever the JVM is running out of memory it will remove those oldest elements. Make sure the limit is large enough so that removing them will actually free enough memory. All the others will still remain in memory and can be used. However, if some other component of the same application uses lots of memory it can happen that your log gets emptied completely.

The Name

I just call it weak ass list because it sounds funny. We can say that a list has a head (first element) and a tail (further elements). In this case it has an ass that can be removed at any time.

You probably would not actually use weak references, because in most cases soft references are more useful. So maybe SoftTailQueue would make more sense.

The Code

The Code is on GitHub: gist.github.com/claudemartin/9977caba94e1d8d97edf4b0435d8fea4

All you need is WeakAssQueue.java and you can just add a namespace (Java package). If you plan on working on the code you can also get the JUnit tests, which are in the second file.

Java Assignments are evaluated Left to Right

I think I’ve just found a mistake in the Java Tutorial.

Maybe I’m just being pedantic, but I think I’ve just found a mistake in the Java Tutorial. It claims:

All binary operators except for the assignment operators are evaluated from left to right; assignment operators are evaluated right to left.

The Java™ Tutorials » Language Basics » Operators

What is this supposed to mean? Evaluation from right to left would mean that when you have a line like the following you get the rightmost expression evaluated first:

int x = 42;
x += getNumber();
// The above would be equivalent to:
x = getNumber() + x;

But that’s not how Java actually evaluates this expression. And the JLS 12 (2019-02-08) clearly states in 15.26.2 that “the value of the left-hand operand is saved and then the right-hand operand is evaluated.”

This explains it best:

A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T) ((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once.

JLS 12, 15.26.2 Compound Assignment Operators

So the above code is actually equal to this:

x = (int) (x + getNumber());

Addition is commutative, so it doesn’t matter. But we also have /=, which is not commutative. You can test this by using a static field for x and some side effect (such as System.out.println and some assignment to x) in getNumber().

public class SomeClass {
	static int x = 42;

	public static void main(String[] args) {
		// assignment operators are evaluated right to left?
		x += getNumber();
		// equal to:
		// x = x + getNumber();
		System.out.println(x);
	}

	static int getNumber() {
		System.out.println("getNumber");
		x = Integer.MIN_VALUE;
		return 58;
	}
}

This code will print 100. That’s because the old value of x (42) is used. If x was evaluated after getNumber() you would get -2147483590 instead.

Contrary to that the Tutorial says all assignments are evaluated left to right. But all the assignment operators are  right-associative. That might be the reason for the mix-up.

There are 12 assignment operators; all are syntactically right-associative (they group right-to-left). Thus, a=b=c means a=(b=c), which assigns the value of c to b and then assigns the value of b to a.

JLS 12, 15.26 Assignment Operators

Example:

public static void main(String[] args) {
	int x = 42, y = 58;
	x += y *= x;
	// equal to: 
	// x = x + (y = y*x);
	System.out.println(x);
}

It would not make any sense if they were left-associative.

The Tutorial should be corrected to say:

All binary operators except for the assignment operators are grouped from left to right; assignment operators are grouped right to left.

Or:

All binary operators except for the assignment operators are left-associative; assignment operators are right-associative.

Using WSL from Java

With Windows Subsystem for Linux (WSL) we can now use Linux tools, such as grep, rsync, ssh, and network commands, such as dig and netstat, on Windows directly. No need for cygwin or other 3rd party software.

Here’s an example on how uname is unknown to Windows, but WSL (Ubuntu in my case) knows it:

WSL can be used to run Linux commands, such as uname.

So when writing Java programs you might want to use this feature. There really isn’t much to say about this because youcan just easily use it. But note that WSL probably uses UTF-8 (as most linux systems are using UTF-8) while CMD /U uses UTF-16LE .

I assume you will need 64bit Java. There’s probably a way to run WSL (which is 64bit) from a 32bit executable. But it’s 2019 and I see no reason to run 32bit Java.

Often you run a simple command that returns a single line, such as which or uname. So my function returns a List of Strings, so you can easily get the first line:

System.out.println(execute("wsl uname -a", utf8).get(0));

There’s nothing really special to do. Just use Runtime​.getRuntime()​.exec(cmd) and read from the InputStream (stdout of the process).

You find the code is on pastebin:
https://pastebin.com/nWvEXxmt

Is Java easy?

Java isn’t easy. It’s often more complex than needed. But being easy for beginners shouldn’t be a design goal with high priority.

Should a programming language be easy?

I don’t know why so many educational establishments use Java to teach programming. They often start with Java in the first semester. Even the Oracle tutorials expect the reader to already know some basics.  Java was designed for programmers who already know C/C++ as seen in this example.

The main method is similar to the main function in C and C++; it’s the entry point for your application and will subsequently invoke all the other methods required by your program. [Lesson: A Closer Look at the “Hello World!” Application]

Continue reading “Is Java easy?”

Misconceptions about Dates and Time

Was 1900 a leap year and does every minute have 60 seconds?

In Java we have a new API for Date and Time since Java SE 8. Before that, there was already an API with mutable dates and fore some reason there was a date just for SQL.
Since many were not happy with it there was Joda-Time, which later became the basis for JSR-310 and is now found in the package “java.time”.

Continue reading “Misconceptions about Dates and Time”

Now free of ads

I have my own blog on my own domain now. No more ads.

I have moved the blog from wordpress.com to my own domain. It’s on a managed server on which I run some other sites. So there are no more ads.

The new URL of this blog is:
https://humanoid-readable.claude-martin.ch

This used to be on humanoidreadable.wordpress.com. All old URLs redirect to the new blog as long as I pay them for this service. 

I still have to fix some of the posts. Somehow the format of wordpress keeps changing. Now they have “blocks”, which is nice. But I have to fix all posts that contain code (that’s most of them). Until then the code will contain &lt; instead of < and so on. But at least I now have full control and you don’t get any annoying ads.

Claude

Stalin-Sort

Stalin-Sort using divide and conquer.

I just love this idea:

I     came up with a single pass O(n) sort algorithm I call Stalin-Sort. U iterate   down the list of elements checking if they are in order. Any element which is  out of order is eliminated. At the end u have a sorted list

But when you have an input such as [42,1,2,3,4,5,6] you just get
[42] instead of [1,2,3,4,5,6]. You can get a better result if you use divide and conquer. And that is something Stalin would do, don’t you think? So I implemented a recursive solution in Java. It tries all possible results, which is not a single pass and therefore defeats the purpose of having a fast O(n) algorithm. And my implementation isn’t even in-place. A new data structure has to be created. That’s why I also added an implementation using a linked list, which is what Mathew describes.

The code is on pastebin: https://pastebin.com/rEmvZSiA