Posts

Showing posts with the label java-9

Is there a way to prevent ClosedByInterruptException?

In the following example, I have one file being used by two threads (in the real example I could have any number of threads) import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; public class A { static volatile boolean running = true; public static void main(String[] args) throws IOException, InterruptedException { String name = "delete.me"; new File(name).deleteOnExit(); RandomAccessFile raf = new RandomAccessFile(name, "rw"); FileChannel fc = raf.getChannel(); Thread monitor = new Thread(() -> { try { while (running) { System.out.println(name + " is " + (fc.size() >> 10) + " KB"); try { Thread.sleep(1000); } catch (InterruptedException e) { System.out.println(...

Meaning of lambda () -> { } in Java

I am looking at the following Stack Overflow answer: How to change Spring's @Scheduled fixedDelay at runtime And in the code there is the following line: schedulerFuture = taskScheduler.schedule(() -> { }, this); I would like to know what the lambda () -> {} means in that code. I need to write it without using lambdas. Its a Runnable with an empty run definition. The anonymous class representation of this would be: new Runnable() { @Override public void run() { // could have done something here } } Lamda expression is an anonymous function that allows you to pass methods as arguments or simply, a mechanism that helps you remove a lot of boilerplate code. They have no access modifier(private, public or protected), no return type declaration and no name. Lets take a look at this example. (int a, int b) -> {return a > b} In your case, you can do something like below: schedulerFuture = taskScheduler.schedule(new Runnable() { @Override ...