Advertisement
Guest User

tace

a guest
Mar 24th, 2018
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 19.61 KB | None | 0 0
  1. package Vezbi;
  2. import java.util.*;
  3. import java.util.concurrent.Semaphore;
  4. import java.util.concurrent.locks.Lock;
  5. import java.util.concurrent.locks.ReentrantLock;
  6. import java.*;
  7. public class Poker {
  8.  
  9. public static Semaphore table;
  10. public static Semaphore playersHere;
  11. public static Semaphore dealer;
  12. public static Semaphore end;
  13. public static int playerHere;
  14. public static boolean isEmpty=true;
  15. public static Lock lock = new ReentrantLock();;
  16. public static void init() {
  17. table=new Semaphore(1);
  18. playerHere=0;
  19. playersHere = new Semaphore(6);
  20. dealer = new Semaphore(1);
  21. end = new Semaphore(1);
  22. }
  23.  
  24. public static class Player extends TemplateThread {
  25.  
  26. public Player(int numRuns) {
  27. super(numRuns);
  28. }
  29.  
  30. @Override
  31. public void execute() throws InterruptedException {
  32.  
  33. if (isEmpty){
  34. playerHere++;
  35. }
  36. if (playerHere==6){
  37.  
  38. table.acquire();
  39. state.playerSeat();
  40. isEmpty=false;
  41. lock.lock();
  42. dealer.acquire();
  43. state.dealCards();
  44. dealer.release();
  45. state.play();
  46. playerHere--;
  47. if(playerHere==0){
  48. end.acquire();
  49. state.endRound();
  50. end.release();
  51. table.release();
  52. isEmpty=true;
  53. }
  54. lock.unlock();
  55. }
  56.  
  57. }
  58.  
  59. }
  60.  
  61. public static void main(String[] args) {
  62.  
  63. run();
  64.  
  65. }
  66.  
  67. static PokerState state = new PokerState();
  68.  
  69. public static void run() {
  70. try {
  71. int numRuns = 1;
  72. int numIterations = 1200;
  73.  
  74. HashSet<Thread> threads = new HashSet<Thread>();
  75.  
  76. for (int i = 0; i < numIterations; i++) {
  77. Player c = new Player(numRuns);
  78. threads.add(c);
  79. }
  80.  
  81. init();
  82.  
  83. ProblemExecution.start(threads, state);
  84. } catch (Exception ex) {
  85. ex.printStackTrace();
  86. }
  87. }
  88. }
  89.  
  90. class PokerState extends AbstractState {
  91.  
  92. private static final int PREVIOUS_ROUND_NOT_FINISHED_POINTS = 7;
  93. private static final String PREVIOUS_ROUND_NOT_FINISHED = "Prethodnata grupa nema zavrseno so igrata.";
  94. private static final int NO_6_FINISHED_PLAYERS_POINTS = 7;
  95. private static final String NO_6_FINISHED_PLAYERS = "Nema 6 igraci koi zavrsile so igranje";
  96.  
  97. private static final int PLAYERS_STIL_PLAYING_POINTS = 7;
  98. private static final String PLAYERS_STIL_PLAYING = "Ima uste igraci koi ne zavrsile so igranje";
  99.  
  100. private static final int PLAYING_NOT_PARALLEL_POINTS = 7;
  101. private static final String PLAYING_NOT_PARALLEL = "ne e paralelno igranjeto";
  102.  
  103. private static final int CARDS_NOT_DEALED_POINTS = 7;
  104. private static final String CARDS_NOT_DEALED = "Ne moze da igra koga kartite ne se podeleni";
  105.  
  106. private static final int MAXIMUM_6_CUSTOMERS_POINTS = 7;
  107. private static final String MAXIMUM_6_CUSTOMERS = "Poveke od 6 igraci probuvaat da sednat istovremeno";
  108.  
  109. private static final int NOT_ENOUGH_PLAYERS_POINTS = 7;
  110. private static final String NOT_ENOUGH_PLAYERS = "nema dovolno igraci za da se sostavi grupa";
  111.  
  112. private BoundCounterWithRaceConditionCheck playersAtTable;
  113. private BoundCounterWithRaceConditionCheck peoplePlaying;
  114. private BoundCounterWithRaceConditionCheck peopleFinishedPlaying;
  115. private boolean emptyTable = true;
  116. private boolean cardsDealed = false;
  117.  
  118. public PokerState() {
  119. playersAtTable = new BoundCounterWithRaceConditionCheck(0, 6,
  120. MAXIMUM_6_CUSTOMERS_POINTS, MAXIMUM_6_CUSTOMERS, null, 0, null);
  121.  
  122. peoplePlaying = new BoundCounterWithRaceConditionCheck(0);
  123. peopleFinishedPlaying = new BoundCounterWithRaceConditionCheck(0);
  124. }
  125.  
  126. /*
  127. * Igracot sednuva na masata
  128. */
  129. public void playerSeat() {
  130. synchronized (PokerState.class) {
  131. if (emptyTable) {
  132. emptyTable = false;
  133. playersAtTable.assertEquals(0,
  134. PREVIOUS_ROUND_NOT_FINISHED_POINTS,
  135. PREVIOUS_ROUND_NOT_FINISHED);
  136. }
  137. }
  138. log(playersAtTable.incrementWithMax(false), "Igrac sednuva");
  139. Switcher.forceSwitch(5);
  140. }
  141.  
  142. /*
  143. * Dilerot deli karti
  144. */
  145. public void dealCards() {
  146. log(playersAtTable.assertEquals(6, NOT_ENOUGH_PLAYERS_POINTS,
  147. NOT_ENOUGH_PLAYERS), null);
  148. synchronized (PokerState.class) {
  149. cardsDealed = true;
  150. }
  151. Switcher.forceSwitch(5);
  152. }
  153.  
  154. /*
  155. * Igracot zapocnuva so igrata
  156. */
  157. public void play() {
  158. synchronized (PokerState.class) {
  159. if (!cardsDealed) {
  160. log(new PointsException(CARDS_NOT_DEALED_POINTS,
  161. CARDS_NOT_DEALED), null);
  162. }
  163. }
  164. log(peoplePlaying.incrementWithMax(false), "Igracot igra poker");
  165. Switcher.forceSwitch(10);
  166. log(peoplePlaying.decrementWithMin(false), null);
  167. peopleFinishedPlaying.incrementWithMax(false);
  168. }
  169.  
  170. /*
  171. * Site igraci zavrsile so igranjeto, moze da vleze nova grupa
  172. */
  173. public void endRound() {
  174. peopleFinishedPlaying.assertEquals(6, NO_6_FINISHED_PLAYERS_POINTS,
  175. NO_6_FINISHED_PLAYERS);
  176. log(peoplePlaying.assertEquals(0, PLAYERS_STIL_PLAYING_POINTS,
  177. PLAYERS_STIL_PLAYING), "Site igraci zavrsija so igranje.");
  178.  
  179. synchronized (PokerState.class) {
  180. // reset scenario
  181. emptyTable = true;
  182. cardsDealed = false;
  183. playersAtTable.setValue(0);
  184. peopleFinishedPlaying.setValue(0);
  185. }
  186. Switcher.forceSwitch(3);
  187. }
  188.  
  189. @Override
  190. public void finalize() {
  191. if (peoplePlaying.getMax() == 1) {
  192. logException(new PointsException(PLAYING_NOT_PARALLEL_POINTS,
  193. PLAYING_NOT_PARALLEL));
  194. }
  195.  
  196. }
  197.  
  198. }
  199.  
  200. abstract class AbstractState {
  201.  
  202. /**
  203. * Method called after threads ended their execution to validate the
  204. * correctness of the scenario
  205. */
  206. public abstract void finalize();
  207.  
  208. /**
  209. * List of logged actions
  210. */
  211. private List<String> actions = new ArrayList<String>();
  212.  
  213. /**
  214. *
  215. * @return if the current thread is instance of TemplateThread it is
  216. * returned, and otherwise null is returned
  217. */
  218. protected TemplateThread getThread() {
  219. Thread current = Thread.currentThread();
  220. if (current instanceof TemplateThread) {
  221. TemplateThread t = (TemplateThread) current;
  222. return t;
  223. } else {
  224. return null;
  225. }
  226. }
  227.  
  228. /**
  229. * Log this exception or action
  230. *
  231. * @param e
  232. * occurred exception (null if no exception)
  233. * @param action
  234. * Description of the occurring action
  235. */
  236. public synchronized void log(PointsException e, String action) {
  237. TemplateThread t = (TemplateThread) Thread.currentThread();
  238. if (e != null) {
  239. t.setException(e);
  240. actions.add(t.toString() + "\t(e): " + e.getMessage());
  241. throw e;
  242. } else if (action != null) {
  243. actions.add(t.toString() + "\t(a): " + action);
  244. }
  245. }
  246.  
  247. /**
  248. * Logging exceptions
  249. *
  250. * @param e
  251. */
  252. protected synchronized void logException(PointsException e) {
  253. Thread t = Thread.currentThread();
  254. if (e != null) {
  255. if (t instanceof TemplateThread) {
  256. ((TemplateThread) t).setException(e);
  257. }
  258. TemplateThread.hasException = true;
  259. actions.add("\t(e): " + e.getMessage());
  260. throw e;
  261. }
  262. }
  263.  
  264. /**
  265. * Printing of the actions and exceptions that has occurred
  266. */
  267. public synchronized void printLog() {
  268. System.out
  269. .println("Poradi konkurentnosta za pristap za pecatenje, mozno e nekoja od porakite da ne e na soodvetnoto mesto.");
  270. System.out.println("Log na izvrsuvanje na akciite:");
  271. System.out.println("=========================");
  272. System.out.println("tip\tid\titer\takcija/error");
  273. System.out.println("=========================");
  274. for (String l : actions) {
  275. System.out.println(l);
  276. }
  277. }
  278.  
  279. /**
  280. * Prints the status of the execution, with the exceptions that has occur
  281. */
  282. public void printStatus() {
  283. try {
  284. finalize();
  285. } catch (Exception e) {
  286. e.printStackTrace();
  287. }
  288. if (!TemplateThread.hasException) {
  289. int poeni = 25;
  290. if (PointsException.getTotalPoints() == 0) {
  291. System.out
  292. .println("Procesot e uspesno sinhroniziran. Osvoeni 25 poeni.");
  293. } else {
  294. poeni -= PointsException.getTotalPoints();
  295. PointsException.printErrors();
  296. System.out.println("Maksimalni osvoeni poeni: " + poeni);
  297. }
  298.  
  299. } else {
  300. System.out
  301. .println("Procesot ne e sinhroniziran spored uslovite na zadacata");
  302. printLog();
  303. System.out
  304. .println("====================================================");
  305. PointsException.printErrors();
  306. int total = (25 - PointsException.getTotalPoints());
  307. if (total < 0) {
  308. total = 0;
  309. }
  310. System.out.println("Maksimum Poeni: " + total);
  311. }
  312.  
  313. }
  314. }
  315.  
  316. class PointsException extends RuntimeException {
  317.  
  318. private static HashMap<String, PointsException> exceptions = new HashMap<String, PointsException>();
  319. private int points;
  320.  
  321. public PointsException(int points, String message) {
  322. super(message);
  323. this.points = points;
  324. exceptions.put(message, this);
  325. }
  326.  
  327. public static int getTotalPoints() {
  328. int sum = 0;
  329. for (PointsException e : exceptions.values()) {
  330. sum += e.getPoints();
  331. }
  332. return sum;
  333. }
  334.  
  335. public static void printErrors() {
  336. if (!exceptions.isEmpty()) {
  337. System.out.println("Gi imate slednite greski: ");
  338. for (Map.Entry<String, PointsException> e : exceptions.entrySet()) {
  339. System.out.println(String.format("[%s] : (-%d)", e.getKey(), e
  340. .getValue().getPoints()));
  341. }
  342. }
  343. }
  344.  
  345. public int getPoints() {
  346. return points;
  347. }
  348. }
  349.  
  350. class Switcher {
  351. private static final Random RANDOM = new Random();
  352.  
  353. /*
  354. * This method pauses the current thread i.e. changes its state to be
  355. * Blocked. This should force thread switch if there are threads waiting
  356. */
  357. public static void forceSwitch(int range) {
  358. try {
  359. Thread.sleep(RANDOM.nextInt(range));
  360. } catch (InterruptedException e) {
  361. }
  362. }
  363. }
  364.  
  365. abstract class TemplateThread extends Thread {
  366.  
  367. static boolean hasException = false;
  368. public int iteration = 0;
  369. protected Exception exception = null;
  370. int numRuns = 1;
  371.  
  372. public TemplateThread(int numRuns) {
  373. this.numRuns = numRuns;
  374. }
  375.  
  376. public abstract void execute() throws InterruptedException;
  377.  
  378. @Override
  379. public void run() {
  380. try {
  381. for (int i = 0; i < numRuns && !hasException; i++) {
  382. execute();
  383. iteration++;
  384.  
  385. }
  386. } catch (InterruptedException e) {
  387. // Do nothing
  388. } catch (Exception e) {
  389. exception = e;
  390. e.printStackTrace();
  391. hasException = true;
  392. }
  393. }
  394.  
  395. public void setException(Exception exception) {
  396. this.exception = exception;
  397. hasException = true;
  398. }
  399.  
  400. @Override
  401. public String toString() {
  402. Thread current = Thread.currentThread();
  403. if (numRuns > 1) {
  404. return String.format("[%d]%s\t%d\t%d", new Date().getTime(), ""
  405. + current.getClass().getSimpleName().charAt(0), getId(),
  406. iteration);
  407. } else {
  408. return String.format("[%d]%s\t%d\t", new Date().getTime(), ""
  409. + current.getClass().getSimpleName().charAt(0), getId());
  410. }
  411. }
  412. }
  413.  
  414. class BoundCounterWithRaceConditionCheck {
  415.  
  416. private static final int RACE_CONDITION_POINTS = 25;
  417. private static final String RACE_CONDITION_MESSAGE = "Race condition occured";
  418.  
  419. private int value;
  420. private Integer maxAllowed;
  421. private Integer minAllowed;
  422. private int maxErrorPoints;
  423. private int minErrorPoints;
  424. private String maxErrorMessage;
  425. private String minErrorMessage;
  426.  
  427. public static int raceConditionDefaultTime = 3;
  428.  
  429. private int max;
  430.  
  431. /**
  432. *
  433. * @param value
  434. */
  435. public BoundCounterWithRaceConditionCheck(int value) {
  436. super();
  437. this.value = value;
  438. this.max = value;
  439. }
  440.  
  441. /**
  442. *
  443. * @param value
  444. * initial value
  445. * @param maxAllowed
  446. * upper bound of the value
  447. * @param maxErrorPoints
  448. * how many points are lost with the max value constraint
  449. * violation
  450. * @param maxErrorMessage
  451. * message shown when the upper bound constrain is violated
  452. * @param minAllowed
  453. * lower bound of the value
  454. * @param minErrorPoints
  455. * how many points are lost with the min value constraint
  456. * violation
  457. * @param minErrorMessage
  458. * message shown when the lower bound constrain is violated
  459. */
  460. public BoundCounterWithRaceConditionCheck(int value, Integer maxAllowed,
  461. int maxErrorPoints, String maxErrorMessage, Integer minAllowed,
  462. int minErrorPoints, String minErrorMessage) {
  463. super();
  464. this.value = value;
  465. this.max = value;
  466. this.maxAllowed = maxAllowed;
  467. this.minAllowed = minAllowed;
  468. this.maxErrorPoints = maxErrorPoints;
  469. this.minErrorPoints = minErrorPoints;
  470. this.maxErrorMessage = maxErrorMessage;
  471. this.minErrorMessage = minErrorMessage;
  472. }
  473.  
  474. /**
  475. *
  476. * @return the maximum value of the integer variable that occurred at some
  477. * point of the execution
  478. */
  479. public int getMax() {
  480. return max;
  481. }
  482.  
  483. /**
  484. *
  485. * @return the current value
  486. */
  487. public synchronized int getValue() {
  488. return value;
  489. }
  490.  
  491. public synchronized void setValue(int value) {
  492. this.value = value;
  493. }
  494.  
  495. /**
  496. * Throws exception when the val is different than the value of the counter.
  497. *
  498. * @param val
  499. * @param points
  500. * @param errorMessage
  501. * @return
  502. */
  503. public synchronized PointsException assertEquals(int val, int points,
  504. String errorMessage) {
  505. if (this.value != val) {
  506. PointsException e = new PointsException(points, errorMessage);
  507. return e;
  508. } else {
  509. return null;
  510. }
  511. }
  512.  
  513. public synchronized PointsException assertNotEquals(int val, int points,
  514. String errorMessage) {
  515. if (this.value == val) {
  516. PointsException e = new PointsException(points, errorMessage);
  517. return e;
  518. } else {
  519. return null;
  520. }
  521. }
  522.  
  523. /**
  524. * Testing for race condition. NOTE: there are no guarantees that the race
  525. * condition will be detected
  526. *
  527. * @return
  528. */
  529. public PointsException checkRaceCondition() {
  530. return checkRaceCondition(raceConditionDefaultTime,
  531. RACE_CONDITION_MESSAGE);
  532. }
  533.  
  534. /**
  535. * Testing for race condition. NOTE: there are no guarantees that the race
  536. * condition will be detected, but higher the time argument is, the
  537. * probability for race condition occurrence is higher
  538. *
  539. * @return
  540. */
  541. public PointsException checkRaceCondition(int time, String message) {
  542. int val;
  543.  
  544. synchronized (this) {
  545. val = value;
  546. }
  547. Switcher.forceSwitch(time);
  548. if (val != value) {
  549. PointsException e = new PointsException(RACE_CONDITION_POINTS,
  550. message);
  551. return e;
  552. }
  553. return null;
  554.  
  555. }
  556.  
  557. public PointsException incrementWithMax() {
  558. return incrementWithMax(true);
  559. }
  560.  
  561. public PointsException incrementWithMax(boolean checkRaceCondition) {
  562. if (checkRaceCondition) {
  563. PointsException raceCondition = checkRaceCondition();
  564. if (raceCondition != null) {
  565. return raceCondition;
  566. }
  567. }
  568. synchronized (this) {
  569. value++;
  570.  
  571. if (value > max) {
  572. max = value;
  573. }
  574. if (maxAllowed != null) {
  575. if (value > maxAllowed) {
  576. PointsException e = new PointsException(maxErrorPoints,
  577. maxErrorMessage);
  578. return e;
  579. }
  580. }
  581. }
  582.  
  583. return null;
  584. }
  585.  
  586. public PointsException decrementWithMin() {
  587. return decrementWithMin(true);
  588. }
  589.  
  590. public PointsException decrementWithMin(boolean checkRaceCondition) {
  591. if (checkRaceCondition) {
  592. PointsException raceCondition = checkRaceCondition();
  593. if (raceCondition != null) {
  594. return raceCondition;
  595. }
  596. }
  597.  
  598. synchronized (this) {
  599. value--;
  600. if (minAllowed != null) {
  601. if (value < minAllowed) {
  602. PointsException e = new PointsException(minErrorPoints,
  603. minErrorMessage);
  604. return e;
  605. }
  606. }
  607. }
  608. return null;
  609. }
  610.  
  611. }
  612.  
  613. abstract class ProblemExecution {
  614.  
  615. public static void start(HashSet<Thread> threads, AbstractState state)
  616. throws Exception {
  617.  
  618. startWithoutDeadlock(threads, state);
  619.  
  620. checkDeadlock(threads, state);
  621. }
  622.  
  623. public static void startWithoutDeadlock(HashSet<Thread> threads,
  624. AbstractState state) throws Exception {
  625.  
  626. // start the threads
  627. for (Thread t : threads) {
  628. t.start();
  629. }
  630.  
  631. // wait threads to finish
  632. for (Thread t : threads) {
  633. t.join(1000);
  634. }
  635.  
  636. }
  637.  
  638. private static void checkDeadlock(HashSet<Thread> threads,
  639. AbstractState state) {
  640. // check for deadlock
  641. for (Thread t : threads) {
  642. if (t.isAlive()) {
  643. t.interrupt();
  644. if (t instanceof TemplateThread) {
  645. TemplateThread tt = (TemplateThread) t;
  646. tt.setException(new PointsException(25, "DEADLOCK"));
  647. }
  648. }
  649. }
  650.  
  651. // print the status
  652. state.printStatus();
  653. }
  654.  
  655. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement