I want to do some stuff in C++ that i can do in Java. Here is my Java code:
interface Worker
{
public void work();
}
class Employer
{
public void askForWork(Worker worker)
{
worker.work();
}
}
public class Main
{
public static void main(String[] args)
{
Employer employer = new Employer();
employer.askForWork(new Worker()
{
#Override
public void work()
{
System.out.println("I'm working!");
}
});
employer.askForWork(new Worker()
{
#Override
public void work()
{
System.out.println("I'm working too!");
}
});
}
}
And I want to do it in C++. It is very important for me to be able to implement interface inside function call. Is it possible?
One way to do it is use std::function.
class Worker {
public:
explicit Worker(std::function<void()> task)
: task_(task) {}
void Work() {
task_();
}
private:
std::function<void()> task_;
};
class Employer {
...
void AskForWork(std::unique_ptr<Worker> worker) {
worker->Work();
}
};
int main(...) {
Employer employer;
employer.AskForWork(new Worker(
[]() {
std::cout << "I'm working!" << std::endl;
}
));
}
Related
How can I determine whether a method is running in another method ?
This is my way.
However, there may be some performance problems.
public class Main {
public static final ThreadLocal<Object> THREAD_LOCAL = new ThreadLocal<>();
public static void main(String[] args) {
f1();
foo(i -> f1());
}
public static void f1() {
Object o = THREAD_LOCAL.get();
if (o == null) {
System.out.println("not in foo");
} else {
System.out.println("in foo");
}
}
public static void foo(Handler<Integer> handler) {
new Thread(() -> {
THREAD_LOCAL.set(new Object());
handler.handle(10);
}).start();
}
public interface Handler<A> {
void handle(A a);
}
}
Is there a better way?
Do not use threads ?
I have three objects: A, B, and C.
I need such synchronization so that blocks synchronized with objects A and B can be executed in parallel, and when block synchronized with objects A or block synchronized with objects B is executed, block synchronized with objects C cannot be executed. And when block synchronized with objects C is executed, blocks synchronized with objects A and B cannot be executed. I tried to use object C as list, and objects A and B as objects stored in this list, but it did not work. Please tell me, is it possible to somehow configure such synchronization?
import java.util.ArrayList;
import java.util.List;
public class Threads {
public List<Res> lst = new ArrayList();
public void startThreads(){
lst.add(new Res());
lst.add(new Res());
Thread t1 = new Thread(new work1());
Thread t2 = new Thread(new work2());
Thread t3 = new Thread(new work3());
t1.start();
t2.start();
t3.start();
}
public class work1 implements Runnable {
#Override
public void run() {
Method1();
}
}
public class work2 implements Runnable {
#Override
public void run() {
Method2();
}
}
public class work3 implements Runnable {
#Override
public void run() {
Method3();
}
}
public void Method1(){
synchronized (lst.get(0)/*obj A*/){
//some work
}
}
public void Method2(){
synchronized (lst.get(1)/*obj B*/){
//some work
}
}
public void Method3(){
synchronized (lst)/*obj C*/{
//some work
}
}
}
Class Res:
public class Res {
public int number = 0;
}
Class Main:
public class Main {
public static void main(String[] args) throws InterruptedException {
Threads t = new Threads();
t.startThreads();
}
}
In your case simplest (Not recommended) solution is to guard Block A and Block B with different monitor objects and guard Block C with the monitor obects of both A and B.
public void Method1(){
synchronized (A){
//some work
}
}
public void Method2(){
synchronized (B){
//some work
}
}
public void Method3(){
synchronized (A){
synchronized (B){
//some work
}
}
}
Same can be done using Locks as well.
public void Method1(){
lockA.lock();
try{
//some work
} finally {
lockA.unlock();
}
}
public void Method2(){
lockB.lock();
try{
//some work
} finally {
lockB.unlock();
}
}
public void Method3(){
lockA.lock();
try{
lockB.lock();
try{
//some work
} finally {
lockB.unlock();
}
} finally {
lockA.unlock();
}
}
Or you can use read/write lock as suggested by shmosel in the comments.
public void Method1(){
readWriteLock.readLock().lock();
try{
//some work
} finally {
readWriteLock.readLock().unlock();
}
}
public void Method2(){
readWriteLock.readLock().lock();
try{
//some work
} finally {
readWriteLock.readLock().unlock();
}
}
public void Method3(){
readWriteLock.writeLock().lock();
try{
//some work
} finally {
readWriteLock.writeLock().unlock();
}
}
You can also use CountDownLatch for the same purpose, though read/write lock is the easiest one.
I read now book Thinking in Java, chapter about critical sections and I cannot understand an example, because I got exceptions which are not described in the book. An example looks like below:
class Pair {
private int x, y;
public Pair(int x, int y) {
this.x = x;
this.y = y;
}
public Pair() {
this(0, 0);
}
public int getX() { return x; }
public int getY() { return y; }
public void incrementX() { x++; }
public void incrementY() { y++; }
public class PairValuesNotEqualException extends RuntimeException {
public PairValuesNotEqualException() {
super("Values are not equal: " + Pair.this);
}
}
public void checkState() {
if (x != y) {
throw new PairValuesNotEqualException();
}
}
}
abstract class PairManager {
AtomicInteger checkCounter = new AtomicInteger(0);
protected Pair p = new Pair();
public synchronized Pair getPair() {
// Make copies to protect the original
return new Pair(p.getX(), p.getY());
}
public abstract void increment();
}
// synchronization of the whole method
class PairManager1 extends PairManager {
#Override
public synchronized void increment() {
p.incrementX();
p.incrementY();
}
}
// Critical section
class PairManager2 extends PairManager {
#Override
public void increment() {
synchronized (this) {
p.incrementX();
p.incrementY();
}
}
}
class PairManipulator implements Runnable {
private PairManager pairManager;
public PairManipulator(PairManager pairManager) {
this.pairManager = pairManager;
}
#Override
public void run() {
while (true)
pairManager.increment();
}
}
class PairChecker implements Runnable {
private PairManager pairManager;
public PairChecker(PairManager pairManager) {
this.pairManager = pairManager;
}
#Override
public void run() {
while (true) {
pairManager.checkCounter.incrementAndGet();
pairManager.getPair().checkState();
}
}
}
public class CriticalSection {
static void testApproaches(PairManager pman1, PairManager pman2) {
ExecutorService exec = Executors.newCachedThreadPool();
PairManipulator
pm1 = new PairManipulator(pman1),
pm2 = new PairManipulator(pman2);
PairChecker
pcheck1 = new PairChecker(pman1),
pcheck2 = new PairChecker(pman2);
exec.execute(pm1);
exec.execute(pm2);
exec.execute(pcheck1);
exec.execute(pcheck2);
try {
TimeUnit.MILLISECONDS.sleep(500);
} catch (InterruptedException e) {
System.out.println("InterruptedException");
}
System.out.println("pm1: " + pm1 + "\npm2: " + pm2);
System.exit(0);
}
public static void main(String[] args) {
PairManager
pman1 = new PairManager1(),
pman2 = new PairManager2();
testApproaches(pman1, pman2);
}
}
An example output:
pm1: Pair: Pair{x=364, y=364} counter = 471421
pm2: Pair: Pair{x=365, y=365} counter = 1015604598
This example executed without exception.
In above example I understand how does it work but the problem is in example with explicit locks.
Example with explicit lock from book:
class ExplicitPairManager1 extends PairManager {
private Lock lock = new ReentrantLock();
// why synchronized ??
public synchronized void increment() {
lock.lock();
try {
p.incrementX();
p.incrementY();
} finally {
lock.unlock();
}
}
}
class ExplicitPairManager2 extends PairManager {
private Lock lock = new ReentrantLock();
public void increment() {
lock.lock();
try {
p.incrementX();
p.incrementY();
} finally {
lock.unlock();
}
}
}
public class ExplicitCriticalSection {
public static void main(String[] args) throws Exception {
PairManager
pm1 = new ExplicitPairManager1(),
pm2 = new ExplicitPairManager2();
CriticalSection.testApproaches(pm1, pm2);
}
}
Output:
Exception in thread "pool-1-thread-4" critical.sections.Pair$PairValuesNotEqualException: Values are not equal: Pair{x=2, y=1}
at critical.sections.Pair.checkState(CriticalSection.java:49)
at critical.sections.PairChecker.run(CriticalSection.java:133)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
pm1: Pair: Pair{x=1024, y=1024} counter = 3
pm2: Pair: Pair{x=1025, y=1025} counter = 1499445
First what I don't understand why author use synchronized in ExplicitPairManager1#increment if he use also Lock object? Is that the mistake in the book?
Second problem is that I don't understand why I got exception?
Excpetion was thrown in:
class PairChecker implements Runnable {
private PairManager pairManager;
public PairChecker(PairManager pairManager) {
this.pairManager = pairManager;
}
#Override
public void run() {
while (true) {
pairManager.checkCounter.incrementAndGet();
pairManager.getPair().checkState(); // here was thrown an exception
}
}
}
Why I got excpetions and author dont? Is that possible JVM behavior is different on different systems? I use Ubuntu 16.04 LTS and Java 8.
You need to synchronize on the same object if you want to establish a critical section for multiple threads.
Your exception is getting thrown for pair modified in ExplicitPairManager2.
Let's see how possible exception-causing flow looks like:
ExplicitPairManager2.lock.lock() gets acquired
ExplicitPairManager2.p.incrementX() happens
PairChecker calls getPair()
PairChecker acquires pairManager's internal (this) monitor, but it is different than ExplicitPairManager2.lock
the result of getPair() therefore has x != y
so in the end there is no critical section.
In other words, while modifying, you were using two different objects to synchronize:
ExplicitPairManager2.lock to write
internal monitor of ExplicitPairManager2 (this) to create a copy for checking state
I was going through Handlers, the post method in it accepts a parameter of type Runnable. There's a following code snippet I came across
final Handler handler = new Handler();
handler.post(new Runnable() {
#Override
public void run() {
timeView.clearComposingText();
Integer hours = seconds/3600;
Integer minutes = (seconds % 3600)/60;
Integer secs = seconds % 60;
String time = String.format("%d:%02d:%02d",hours,minutes,secs);
timeView.setText(time);
if(running)
{
seconds++;
}
handler.postDelayed(this,1000);
}
});
Now since Runnable is an Interface in Java, how are we able to create a new instance of Runnable directly?
Anonymous classes can implement interfaces, and that's the only time you'll see a class implementing an interface without the "implements" keyword.
A complete example might look like:
public class MyClass {
public interface A {
void foo();
}
public interface B {
void bar();
}
public interface C extends A, B {
void baz();
}
public void doIt(C c) {
c.foo();
c.bar();
c.baz();
}
public static void main(String[] args) {
MyClass mc = new MyClass();
mc.doIt(new C() {
#Override
public void foo() {
System.out.println("foo()");
}
#Override
public void bar() {
System.out.println("bar()");
}
#Override
public void baz() {
System.out.println("baz()");
}
});
}
}
The output of this example is:
foo()
bar()
baz()
I am working on a project in which I have multiple interface and two Implementations classes which needs to implement these two interfaces.
Suppose my first Interface is -
public Interface interfaceA {
public String abc() throws Exception;
}
And its implementation is -
public class TestA implements interfaceA {
// abc method
}
I am calling it like this -
TestA testA = new TestA();
testA.abc();
Now my second interface is -
public Interface interfaceB {
public String xyz() throws Exception;
}
And its implementation is -
public class TestB implements interfaceB {
// xyz method
}
I am calling it like this -
TestB testB = new TestB();
testB.xyz();
Problem Statement:-
Now my question is - Is there any way, I can execute these two implementation classes in parallel? I don't want to run it in sequential.
Meaning, I want to run TestA and TestB implementation in parallel? Is this possible to do?
Sure it is possible. You have actually many options. Preferred one is using callable and executors.
final ExecutorService executorService = Executors.newFixedThreadPool(2);
final ArrayList<Callable<String>> tasks = Lists.newArrayList(
new Callable<String>()
{
#Override
public String call() throws Exception
{
return testA.abc();
}
},
new Callable<String>()
{
#Override
public String call() throws Exception
{
return testB.xyz();
}
}
);
executorService.invokeAll(tasks);
This method gives you opportunity to get a result from executions of your tasks. InvokeAll returns a list of Future objects.
final List<Future<String>> futures = executorService.invokeAll(tasks);
for (Future<String> future : futures)
{
final String resultOfTask = future.get();
System.out.println(resultOfTask);
}
You can make your code easier to use if you make your classes implements Callable, then you will reduce amount of code needed to prepare list of tasks. Let's use TestB class as an example:
public interface interfaceB {
String xyz() throws Exception;
}
public class TestB implements interfaceB, Callable<String>{
#Override
public String xyz() throws Exception
{
//do something
return "xyz";
}
#Override
public String call() throws Exception
{
return xyz();
}
}
Then you will need just
Lists.newArrayList(new TestB(), new TestA());
instead of
final ArrayList<Callable<String>> tasks = Lists.newArrayList(
new Callable<String>()
{
#Override
public String call() throws Exception
{
return testA.abc();
}
},
new Callable<String>()
{
#Override
public String call() throws Exception
{
return testB.xyz();
}
}
);
Whats more, executors gives you power to maintain and reuse Thread objects which is good from performance and maintainability perspective.
Create Two Thread and run two implementation parallely. Code snippet -
ThreadA{
public void run(){
TestA testA = new TestA();
testA.abc();
}
}
...
ThreadB{
public void run(){
TestB testB = new TestB();
testB.xyz();
}
}
Start this two thread from main method -
public static void main(String[] args){
new ThreadA().start();
new ThreadB().start();
}
Try this one
Collect all the classes of same interface and call them in Multi threading.
Use Callback mechanism to get the result back
import java.util.ArrayList;
import java.util.List;
public class Demo123 {
public static void main(String[] args) {
List<InterfaceA> a = new ArrayList<InterfaceA>();
List<InterfaceB> b = new ArrayList<InterfaceB>();
TestA testA = new TestA();
TestB testB = new TestB();
a.add(testA);
b.add(testB);
for (final InterfaceA i : a) {
new Thread(new Runnable() {
#Override
public void run() {
try {
i.callback(i.abc());
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
for (final InterfaceB i : b) {
new Thread(new Runnable() {
#Override
public void run() {
try {
i.callback(i.xyz());
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
}
}
interface MyCallback {
public void callback(String value);
}
interface InterfaceA extends MyCallback {
public String abc() throws Exception;
}
class TestA implements InterfaceA {
#Override
public String abc() throws Exception {
return "abc";
}
#Override
public void callback(String value) {
System.out.println("value returned:" + value);
}
}
interface InterfaceB extends MyCallback {
public String xyz() throws Exception;
}
class TestB implements InterfaceB {
#Override
public String xyz() throws Exception {
return "xyz";
}
#Override
public void callback(String value) {
System.out.println("value returned:" + value);
}
}
You may try it like this:
public static void main(String[] args) throws InterruptedException {
Executors.newCachedThreadPool().invokeAll(Arrays.asList(
new Callable<String>() {
#Override public String call() { return new TestA().abc(); }
},
new Callable<String>() {
#Override public String call() { return new TestB().xyz(); }
}));
}
public interface InterfaceA {
public String abc() throws Exception;
}
public interface InterfaceB {
public String xyz() throws Exception;
}
class TestA implements InterfaceA {
#Override public String abc() {
System.out.println("Inside A"); return null;
}
}
class TestB implements InterfaceB {
#Override public String xyz() {
System.out.println("Inside B"); return null;
}
}