Guest User

save

a guest
Dec 28th, 2010
198
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.82 KB | None | 0 0
  1. package server.model.players;
  2.  
  3. import java.util.ArrayList;
  4.  
  5. import server.Server;
  6.  
  7. /**
  8.  * @author Sanity
  9.  */
  10.  
  11. public class PlayerSaving implements Runnable {
  12.    
  13.     private ArrayList<Integer> requests = new ArrayList<Integer>();
  14.     private Thread thread;
  15.     private static PlayerSaving singleton;
  16.     private static long lastGroupSave;
  17.     private static final int SAVE_TIMER = 25000;
  18.    
  19.     public static PlayerSaving getSingleton() {
  20.         return singleton;
  21.     }
  22.    
  23.     public static void initialize() {
  24.         singleton = new PlayerSaving();
  25.         singleton.thread = new Thread(singleton);
  26.         singleton.thread.start();
  27.     }
  28.    
  29.     public synchronized void run() {
  30.         while(true) {
  31.             saveAllPlayers();
  32.             try {
  33.                 thread.sleep(25000);
  34.             } catch (Exception e) {
  35.                 e.printStackTrace();
  36.             }
  37.         }  
  38.     }
  39.    
  40.    
  41.     public synchronized void requestSave(int i) {
  42.         if (!requests.contains(i)) {
  43.             requests.add(i);
  44.             notify();
  45.         }
  46.     }
  47.    
  48.     public void saveAllPlayers() {
  49.         lastGroupSave = System.currentTimeMillis();
  50.         //requests.clear();
  51.         long start = lastGroupSave;
  52.         for (Player p : PlayerHandler.players) {
  53.             if (p != null)
  54.                 PlayerSave.saveGame((Client)p);
  55.             if (System.currentTimeMillis() - start >= (Server.getSleepTimer() - 5)) {
  56.                 System.out.println("Aborted all saving to prevent lag.");
  57.                 return;
  58.             }  
  59.         }
  60.         System.out.println("Saved all games.");
  61.     }
  62.    
  63.     public void saveRequests() {
  64.         int totalSave = 0;
  65.         for (int id : requests) {
  66.             if (PlayerHandler.players[id] != null) {
  67.                 Client c = (Client)PlayerHandler.players[id];
  68.                 PlayerSave.saveGame((Client)PlayerHandler.players[id]);
  69.                 totalSave++;
  70.             }      
  71.         }
  72.         System.out.println("Saved a total of: " + totalSave + " games.");
  73.         requests.clear();
  74.     }
  75.    
  76.     public static boolean saveRequired() {
  77.         return System.currentTimeMillis() - lastGroupSave > SAVE_TIMER;
  78.     }
  79. }
Advertisement
Add Comment
Please, Sign In to add comment