Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save nkonev/da8ab13bc6c5a5ee65da7a69383c02be to your computer and use it in GitHub Desktop.

Select an option

Save nkonev/da8ab13bc6c5a5ee65da7a69383c02be to your computer and use it in GitHub Desktop.
package p;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Created by nkonev on 22.05.17.
*/
public class ImmutableStatelessInterfaceInstanceForThread {
public static void main(String[] args) throws InterruptedException {
// this is lambda which implicitly creates MyRunnable instance with getContext() method which returns new MyRunnable.MyContext
// casting to MyRunnable is required
Thread thread = new Thread((MyRunnable) () -> new MyRunnable.MyContext(666, "Никита"));
thread.start();
thread.join();
}
private interface MyRunnable extends Runnable {
// interface allows only static final which forces you make immutably Runnables
Logger LOGGER = LoggerFactory.getLogger(MyRunnable.class);
MyContext getContext();
@Override
default void run() {
final MyContext c = getContext();
LOGGER.info("hello, #{} {}", c.getId(), c.getName());
}
class MyContext {
private final int id;
private final String name;
public MyContext(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment