Skip to content

New patterns #18

@brunoborges

Description

@brunoborges

Some missing bits:

  • markdown comments
    /// This is a javadoc comment

  • static method in interface (Java 8)

  • static member in inner classes (Java 16)

    class Main {
    class Book {
    static int globalBookCount;

     Book() {
      globalBookCount++;
     }
    

    }
    }

  • compact canonical constructor (for preconditions) (Java 15 ?)

    public record Person(String name, List pets) {
    public {
    Objects.requireNonNull(name);
    pets = List.copyOf(pets);
    }
    }

  • loop over a List in reverse order

    for(Iterator iterator = list.listIerator(list.isze()); iterator.hasPrevious();) {
    String element = iterator.previous();
    ...
    }

vs

for(String element : list.reversed()) {
...
}

  • File mapping in memory

    FileChannel channel = ...
    MappedByteBuffer buffer = channel.map( FileChannel.MapMode.READ_WRITE, 0, (int) channel.size());
    // file size limited to 2G
    // freed by the GC, no control

vs

FileChannel channel = ...
try (Arena arena = Arena.ofShared()) {
MemorySegment segment = channel.map( FileChannel.MapMode.READ_WRITE, 0, channel.size(), arena);
// no file size limit
...
} // call close() => freed

  • The example of "writing files" old style is wrong
    try(BufferedWriter writer = new BufferedWriter(new FileReader(path))) {
    ...
    }

    here if the new BufferedWriterfails to allocate the buffer, close() is not called on the FileReader,
    it should be (using two lines)

    try(FileWriter fileWriter = new FileReader(path);
    BufferedWriter writer = new BufferedWriter(fileWriter)) {
    ...
    }

Metadata

Metadata

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions