Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
JavaDoc optimized
  • Loading branch information
IOAyman committed Jan 23, 2015
commit 9192686c96f0bd98a4152c6755d3d32585620dd9
45 changes: 20 additions & 25 deletions JavaMultiThreadingCodes/src/Deadlock_11/Runner.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,22 +4,23 @@
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
* <a href="https://wikipedia.org/wiki/Deadlock">Deadlock</a>
* <br><br>
* Codes with minor comments are from
* <a href="http://www.caveofprogramming.com/youtube/">
* <em>http://www.caveofprogramming.com/youtube/</em>
* </a>
* <br>
* also freely available at
* <a href="https://www.udemy.com/java-multithreading/?couponCode=FREE">
* <em>https://www.udemy.com/java-multithreading/?couponCode=FREE</em>
* </a>
*
* @author Z.B. Celik <[email protected]>
*/
public class Runner {
/**
* <a href="https://wikipedia.org/wiki/Deadlock">Deadlock</a>
* <br><br>
* Codes with minor comments are from
* <a href="http://www.caveofprogramming.com/youtube/">
* <em>http://www.caveofprogramming.com/youtube/</em>
* </a>
* <br>
* also freely available at
* <a href="https://www.udemy.com/java-multithreading/?couponCode=FREE">
* <em>https://www.udemy.com/java-multithreading/?couponCode=FREE</em>
* </a>
*
* @author Z.B. Celik <[email protected]>
*/
@SuppressWarnings("InfiniteLoopStatement")
public class Runner {

private Account acc1 = new Account();
private Account acc2 = new Account();
Expand All @@ -44,15 +45,9 @@ private void acquireLocks(Lock firstLock, Lock secondLock) throws InterruptedExc
gotFirstLock = firstLock.tryLock();
gotSecondLock = secondLock.tryLock();
} finally {
if (gotFirstLock && gotSecondLock) {
return;
}
if (gotFirstLock) {
firstLock.unlock();
}
if (gotSecondLock) {
secondLock.unlock();
}
if (gotFirstLock && gotSecondLock) return;
else if (gotFirstLock) firstLock.unlock();
else if (gotSecondLock) secondLock.unlock();
}
// Locks not acquired
Thread.sleep(1);
Expand Down
10 changes: 5 additions & 5 deletions JavaMultiThreadingCodes/src/Deadlock_11/SimpleDeadLock.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@

/**
* Source: http://www.herongyang.com/Java/Deadlock-What-Is-Deadlock.html
* Deadlock is a programming situation where two or more threads are blocked
* <p>
* <a href="https://wikipedia.org/wiki/Deadlock">Deadlock</a>
* is a programming situation where two or more threads are blocked
* forever, this situation arises with at least two threads and two or more
* resources.
*
Expand All @@ -28,8 +30,7 @@ public void run() {
System.out.println("Thread 1: Holding lock 1...");
try {
Thread.sleep(10);
} catch (InterruptedException ignored) {
}
} catch (InterruptedException ignored) {}
System.out.println("Thread 1: Waiting for lock 2...");
synchronized (lock2) {
System.out.println("Thread 2: Holding lock 1 & 2...");
Expand All @@ -45,8 +46,7 @@ public void run() {
System.out.println("Thread 2: Holding lock 2...");
try {
Thread.sleep(10);
} catch (InterruptedException ignored) {
}
} catch (InterruptedException ignored) {}
System.out.println("Thread 2: Waiting for lock 1...");
synchronized (lock1) {
System.out.println("Thread 2: Holding lock 2 & 1...");
Expand Down
47 changes: 30 additions & 17 deletions JavaMultiThreadingCodes/src/Semaphores_12/App.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,48 +5,61 @@
import java.util.concurrent.TimeUnit;

/**
* Semaphores are mainly used to limit the number of simultaneous threads that
* {@link java.util.concurrent.Semaphore}s
* are mainly used to limit the number of simultaneous threads that
* can access a resources, but you can also use them to implement deadlock
* recovery systems since a semaphore with one permit is basically a lock that
* you can unlock from other threads.
*
* can unlock from other threads.
* <br>
* Source:
* <a href="http://stackoverflow.com/questions/771347/what-is-mutex-and-semaphore-in-java-what-is-the-main-difference">
* http://stackoverflow.com/questions/771347/what-is-mutex-and-semaphore-in-java-what-is-the-main-difference
*
* Mutex is basically mutual exclusion. Only one thread can acquire the resource
* at once. When one thread acquires the resource, no other thread is allowed to
* acquire the resource until the thread owning the resource releases. All
* threads waiting for acquiring resource would be blocked.
*
* </a>
* <p>
* Mutex (or a semaphore initialized to 1; meaning there's only one resource)
* is basically a mutual exclusion; Only one thread can acquire the resource
* at once, and all other threads trying to acquire the resource are blocked
* until the thread owning the resource releases.
* <p>
* Semaphore is used to control the number of threads executing. There will be
* fixed set of resources. The resource count will gets decremented every time
* when a thread owns the same. When the semaphore count reaches 0 then no other
* threads are allowed to acquire the resource. The threads get blocked till
* other threads owning resource releases.
*
* </p>
* <p>
* In short, the main difference is how many threads are allowed to acquire the
* resource at once ?
*
* resource at once.
* TODO -- go a little more in depth explaining that
* Mutex --its ONE. Semaphore -- its DEFINED_COUNT, ( as many as semaphore
* count)
*
* Codes with minor comments are from http://www.caveofprogramming.com/youtube/
* </p>
* <br><br>
* Codes with minor comments are from
* <a href="http://www.caveofprogramming.com/youtube/">
* <em>http://www.caveofprogramming.com/youtube/</em>
* </a>
* <br>
* also freely available at
* https://www.udemy.com/java-multithreading/?couponCode=FREE
* <a href="https://www.udemy.com/java-multithreading/?couponCode=FREE">
* <em>https://www.udemy.com/java-multithreading/?couponCode=FREE</em>
* </a>
*
* @author Z.B. Celik <[email protected]>
*/
public class App {

public static void main(String[] args) throws Exception {
ExecutorService executor = Executors.newCachedThreadPool();
for (int i = 0; i < 13; i++) { //200 hundred times will be called

for (int i = 0; i < 20; i++) { //200 hundred times will be called
executor.submit(new Runnable() {
public void run() {
Connection.getInstance().connect();
Connectionn.getInstance().connect();
}
});
}

executor.shutdown();
executor.awaitTermination(1, TimeUnit.DAYS);
}
Expand Down
51 changes: 35 additions & 16 deletions JavaMultiThreadingCodes/src/Semaphores_12/Connection.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,38 @@

/**
* Semaphores
*
* Codes with minor comments are from http://www.caveofprogramming.com/youtube/
* <br><br>
* Codes with minor comments are from
* <a href="http://www.caveofprogramming.com/youtube/">
* <em>http://www.caveofprogramming.com/youtube/</em>
* </a>
* <br>
* also freely available at
* https://www.udemy.com/java-multithreading/?couponCode=FREE
* <a href="https://www.udemy.com/java-multithreading/?couponCode=FREE">
* <em>https://www.udemy.com/java-multithreading/?couponCode=FREE</em>
* </a>
*
* @author Z.B. Celik <[email protected]>
*/
public class Connection {

private static Connection instance = new Connection();
//limit connections to 10
//true means whichever the thread call the acquire first gets it first,
//in queue placed first to obtain the permit.
/*
limit connections to 10
true means whichever thread gets first in the waiting pool (queue)
waiting to acquire a resource, is first to obtain the permit.

Note that I called it a pool!
The reason is when you say "Queue", you're saying that things are
scheduled to be FIFO (First In First Out) .. which is not always the case
here!
When you initialize the semaphore with Fairness, by setting its second
argument to true, it will treat the waiting threads like FIFO.
But,
it doesn't have to be that way if you don't set on the fairness. the JVM
may schedule the waiting threads in some other manner that it sees best
(See the Java specifications for that).
*/
private Semaphore sem = new Semaphore(10, true);
private int connections = 0;

Expand All @@ -29,16 +48,18 @@ public static Connection getInstance() {

public void connect() {
try {
sem.acquire(); // get permit decrease the sem value, if 0 wait for release
} catch (InterruptedException e1) {
e1.printStackTrace();
}
try {

// get permit decrease the sem value, if 0 wait for release
sem.acquire();

//if doConnect throws and exception is still releases the permit
//so we use a separate method here to increase the connections count.
//so we use a separate method here to increase the connections count
doConnect();

} catch (InterruptedException ignored) {
} finally {
sem.release();// release permit, increase the sem value and activate waiting thread
//release permit, increase the sem value and activate waiting thread
sem.release();
}
}

Expand All @@ -51,9 +72,7 @@ public void doConnect() {
//do your job
System.out.println("Working on connections " + Thread.currentThread().getName());
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
} catch (InterruptedException ignored) {}
//when exit doConnect method decrement number of connections
synchronized (this) {//atomic
connections--;
Expand Down
73 changes: 73 additions & 0 deletions JavaMultiThreadingCodes/src/Semaphores_12/Connectionn.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
package Semaphores_12;

import java.util.concurrent.Semaphore;

/**
* Semaphores
* <br><br>
* Codes with minor comments are from
* <a href="http://www.caveofprogramming.com/youtube/">
* <em>http://www.caveofprogramming.com/youtube/</em>
* </a>
* <br>
* also freely available at
* <a href="https://www.udemy.com/java-multithreading/?couponCode=FREE">
* <em>https://www.udemy.com/java-multithreading/?couponCode=FREE</em>
* </a>
*
* @author Z.B. Celik <[email protected]>
*/
public class Connectionn {

private static Connectionn instance = new Connectionn();
/*
limit connections to 10
true means whichever thread gets first in the waiting pool (queue)
waiting to acquire a resource, is first to obtain the permit.

Note that I called it a pool!
The reason is when you say "Queue", you're saying that things are
scheduled to be FIFO (First In First Out) .. which is not always the case
here!
When you initialize the semaphore with Fairness, by setting its second
argument to true, it will treat the waiting threads like FIFO.
But,
it doesn't have to be that way if you don't set on the fairness. the JVM
may schedule the waiting threads in some other manner that it sees best
(See the Java specifications for that).
*/
private Semaphore sem = new Semaphore(10, true);

private Connectionn() {
}

public static Connectionn getInstance() {
return instance;
}

public void connect() {
try {

// get permit decrease the sem value, if 0 wait for release
sem.acquire();

System.out.printf("%s:: Current connections (max 10 allowed): %d\n",
Thread.currentThread().getName(),
sem.availablePermits());

//do your job
System.out.printf("%s:: WORKING...\n",
Thread.currentThread().getName());
Thread.sleep(2000);

System.out.printf("%s:: Connection released. Permits Left = %d\n",
Thread.currentThread().getName(),
sem.availablePermits());

} catch (InterruptedException ignored) {
} finally {
//release permit, increase the sem value and activate waiting thread
sem.release();
}
}
}